这些是 JavaScript 的两个模块系统,用于将代码分解到多个文件中。
ES Modules (ESM) — 现代标准
js
// import / export, used in browsers and modern Node
import { sum } from "./math.js";
import defaultThing from "./thing.js";
export const x = 1;
export default function () {};
这些是 JavaScript 的两个模块系统,用于将代码分解到多个文件中。
// import / export, used in browsers and modern Node
import { sum } from "./math.js";
import defaultThing from "./thing.js";
export const x = 1;
export default function () {};
const { sum } = require("./math");
module.exports = { x: 1 };
| ES Modules | CommonJS | |
|---|---|---|
| Syntax | import/export | require/module.exports |
| Loading | static, async | dynamic, synchronous |
| Analyzable | ✅ → tree-shaking | ❌ harder |
| Bindings | live (read-only) | 复制的值 |
this at top | undefined | module.exports |
Static 意味着 ESM 导入在解析时已知,这使得打包工具可以执行 tree-shaking(丢弃未使用的导出)。CommonJS require 是动态的(你可以有条件地 require),所以它不容易被分析。
{ "type": "module" } // in package.json, or use the .mjs extension
你不能从 CommonJS 中 require() 仅限 ESM 的包;混合两者会有粗糙的边界。ESM 导入也是 live bindings — 如果导出者改变值,导入者会看到新值(CJS 给你一个快照副本)。
ESM 是未来(浏览器原生、可 tree-shake、顶级 await)。
对新代码优先使用它;理解 CJS 是因为 Node 生态系统中的大部分仍在使用它。