Dưới đây là mã để đổi tên (rename) khi import và export module trong JavaScript.
Lưu ý: Cần chạy localhost server để chạy ví dụ này (do module ES yêu cầu CORS).
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Rename import export</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Đổi tên import và export trong JavaScript</h1> <div class="result"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để thực thi hàm đã import</h3> <script src="script.js" type="module"></script> </body> </html>
script.js
import {test, tellTime as showTime} from "./sample.js"; let resultEle = document.querySelector('.result'); document.querySelector('.Btn').addEventListener('click',()=>{ resultEle.innerHTML+=test(); resultEle.innerHTML+=showTime(); })
sample.js
function testImport() { return "Module testImport đã được import" + "<br>"; } function tellTime() { return new Date(); } export { testImport as test, tellTime };
Kết quả
Khi nhấn nút, hiển thị thông báo import thành công và thời gian hiện tại.
Cú pháp as cho phép đổi tên khi export (export { testImport as test }) và khi import (import { tellTime as showTime }). Điều này tránh xung đột tên và làm rõ ý định.