ES Modules (ESM) là hệ thống module chuẩn của JavaScript, chạy được ở trình duyệt, Node.js, Deno, Bun. Mỗi file là một module với phạm vi riêng — biến không tự lọt ra ngoài.
// Named export
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
export { subtract, subtract as minus }; // export kèm đổi tên
// Default export — tối đa một cái mỗi module
export default function multiply(a, b) {
return a * b;
}import multiply, { PI, add, minus as sub } from "./math.js";
import * as math from "./math.js"; // namespace object
multiply(2, 3); // 6
math.add(1, 2); // 3TIP
Nhiều team ưu tiên named export: tên nhất quán ở mọi nơi import, IDE tự gợi ý và refactor tốt hơn. Default export hợp khi module chỉ có đúng một thứ chính (một component, một class).
export { formatMoney } from "./money.js";
export * from "./date.js";
export * as validators from "./validators.js";NOTE
Barrel file tiện nhưng có thể làm chậm build/test và cản tree-shaking trong dự án lớn. Dùng vừa phải.
import/export là tĩnh: chỉ ở cấp cao nhất, đường dẫn là chuỗi cố định → công cụ phân tích được, bundler loại bỏ được code không dùng (tree-shaking)../math.js, không phải ./math).import() là một hàm trả về Promise — dùng để tải module khi cần (code splitting, tải theo điều kiện):
button.addEventListener("click", async () => {
const { openEditor } = await import("./editor.js");
openEditor();
});
const locale = navigator.language.startsWith("vi") ? "vi" : "en"
Node.js coi file là ESM khi: đuôi .mjs, hoặc .js nằm trong package có "type": "module".
{
"name": "my-app",
"type": "module"
}Import module có sẵn của Node bằng tiền tố node::
import { readFile } from "node:fs/promises";
import path from "node:path";NOTE
CommonJS (require/module.exports) là hệ thống cũ của Node.js, vẫn còn rất nhiều trong hệ sinh thái. Code mới nên viết ESM. Các bản Node.js hiện đại còn cho phép require() một module ESM (miễn là module đó không dùng top-level await), giúp việc chuyển đổi dễ hơn.
Comments