ES Modules: import { name } from 'module' (named import). import { name as alias } đổi tên. import defaultExport from 'module' (default import). File export: export { name } hoặc export default.
Ví dụ
Import test và tellTime as showTime từ sample.js:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ES Module Import</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>Dùng { } trong JavaScript Import (Named Import)</h1>
<div class="result"></div>
<button class="Btn">THỰC THI IMPORT</button>
<h3>Nhấn nút để chạy hàm import từ module</h3>
<script type="module">
import { test, tellTime as showTime } from './sample.js';
const resultEle = document.querySelector('.result');
document.querySelector('.Btn').addEventListener('click', () => {
resultEle.innerHTML += test() + '<br>';
resultEle.innerHTML += showTime();
});
</script>
</body>
</html>
sample.js
function testImport() { return 'Module testImport đã được import'; }
function tellTime() { return new Date().toLocaleString('vi-VN'); }
export { testImport as test, tellTime };
Kết quả
Hiển thị: "Module testImport đã được import" và thời gian hiện tại.
Lưu ý: Cần chạy trên HTTP server (localhost) do CORS policy của ES Module. Không chạy trực tiếp file file://.