Khái niệm
ES Modules (ESM) (ES2015) cho phép chia code thành nhiều file nhỏ, độc lập, sử dụng export và import. Giúp quản lý dependency, tránh污染 global scope, và hỗ trợ tree-shaking.
Đặc điểm chính
- Chạy ở chế độ strict mode mặc định
- Mỗi module có scope riêng
- Load bất đồng bộ (async), defer mặc định
- Cần chạy qua HTTP server (localhost), không mở file trực tiếp
Cấu trúc ví dụ (3 file)
1. index.html
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES Modules</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.result { font-size: 18px; font-weight: 500; color: #6a1b9a; margin-top: 20px; padding: 15px; background: #f3e5f5; border-radius: 4px; }
button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h1>Modules trong JavaScript</h1>
<button id="btn">IMPORT MODULE</button>
<div class="result" id="result"></div>
<h3>Nhấn nút để import module</h3>
<!-- type="module" quan trọng -->
<script src="script.js" type="module"></script>
</body>
</html>
2. sample.js (Module xuất khẩu)
// sample.js
const resultEle = document.querySelector('.result');
// Named export
export function greet(name) {
return `Xin chào ${name}!`;
}
// Default export
export default function testImport() {
resultEle.innerHTML = '✅ Module testImport đã được import';
return 'Default export thành công';
}
3. script.js (Module nhập khẩu)
// script.js
import testImport, { greet } from './sample.js';
document.getElementById('btn').addEventListener('click', () => {
// Gọi default export
testImport();
// Gọi named export
const msg = greet('Lập trình viên');
console.log(msg); // "Xin chào Lập trình viên!"
});
Các loại Export/Import
| Loại | Export | Import | Số lượng/file |
|---|---|---|---|
| Default | export default ... | import tenBatKy from './file' | 1 |
| Named | export const/ function ... | import { tenChinhXac } from './file' | Nhiều |
| Namespace | - | import * as ns from './file' | - |
| Rename | - | import { old as new } from './file' | - |
Dynamic Import (Lazy Loading)
// Tải module khi cần (code splitting)
button.addEventListener('click', async () => {
const { heavyFunction } = await import('./heavy-module.js');
heavyFunction();
});
Chạy ví dụ
- Tạo 3 file như trên trong cùng thư mục
- Chạy local server:
npx servehoặcpython -m http.serverhoặc Live Server VS Code - Mở
https://localhost:port
Lưu ý: Không mở file HTML trực tiếp (file://) - sẽ lỗi CORS.