Node.js 模块导入
系统对比 CommonJS 与 ES Modules(ESM)的导出/导入语法、加载机制、严格模式、双向互操作方式及 Node.js v24 原生 require(esm) 实测行为。
学完这一章,你能够
- 系统对比 CommonJS 与 ES Modules(ESM)的导出/导入语法、加载机制、严格模式、双向互操作方式及 Node.js v24 原生 require(esm) 实测行为。
Node.js 双模块体系概览
在 Node.js 项目中,模块化通过把可复用代码拆分为独立 JavaScript 文件并按约定导入导出实现。当前生态并存两套模块体系:早期源自服务端社区的 CommonJS(CJS)与 JavaScript 语言官方标准 ES Modules(ESM)。
CommonJS 模块系统用法与特性
CommonJS 使用 `module.exports` 或 `exports` 导出、用 `require()` 同步导入。既可整体导出对象或函数(如 `module.exports = { add }`),也可逐项挂载具名属性(如 `exports.name = 'Alice'`),导入侧可整包接收或直接解构属性。本站 Node.js v24.22.3 实测加载临时 `.cjs` 模块求得 `add(2, 3) === 5`,解构取得 `{ name: 'Alice', age: 30 }`。
CommonJS 具有三项典型特点:同步加载契合本地磁盘读取速度;属于运行时加载,允许在条件分支或函数体内动态调用 `require()`;内置模块缓存机制,重复导入同一路径直接返回缓存引用(实测条件分支二次 `require('./math.cjs')` 命中同一对象 `cacheHit: true`)。
ES Module(ESM)规范用法与特性
ESM 是 ECMAScript 官方标准,采用 `import` 与 `export` 语法。在 Node.js 中启用 ESM 有两种常见方式:将文件扩展名命名为 `.mjs`,或在最近上层 `package.json` 中声明 `"type": "module"`(相应地,在该目录下若需显式编写 CommonJS 文件则使用 `.cjs` 后缀)。
ESM 同时支持具名导出(`export const name = ...` / `export function add()`)与默认导出(`export default ...`),导入侧可单独导入具名成员、默认导出、同时导入两者,或用 `import * as ns` 收集完整命名空间(默认导出挂载在 `ns.default`)。其核心特性包括:模块图异步解析加载(支持顶层 `await`)、编译期静态分析依赖以利 Vite/Webpack 执行 Tree Shaking,以及默认启用严格模式。实测动态导入临时 `.mjs` 模块确认 `add(2,3)=5`、`default(2,3)=6`、严格模式下普通函数内 `this === undefined`(`esmStrictMode: true`)且命名空间键为 `['age', 'default', 'isStrict', 'name']`。
CommonJS 与 ESM 对比、互操作与选型建议
同一项目可并存两类模块,但不能在单一文件内混写两套顶层语法(ESM 文件内不能直接调用未声明的 `require`/`module.exports`,CJS 文件内不能写静态 `import`/`export`)。跨体系互操作规则如下:1)在 ESM 中导入 CommonJS 模块,可直接 `import cjsMod from './mod.cjs'`,CJS 的 `module.exports` 会作为默认导出暴露(实测 `importedCjs.default.data === 'hello'`);2)在 CommonJS 中导入任意 ESM 模块,通用方式是使用返回 Promise 的动态 `await import('./mod.mjs')`(实测成功取得 `{ name: 'Bob', greeting: 'Hello, my name is Bob.' }`);3)值得补充的是,Node.js v24 已默认启用同步 `require(esm)` 互操作——只要目标 ESM 模块不包含顶层 `await`,CommonJS 现可直接同步 `require()` 加载并读取其命名空间,而对包含顶层 `await` 的 ESM 调用 `require()` 则明确抛出 `ERR_REQUIRE_ASYNC_MODULE`(本站 v24.22.3 双向实测均已验证)。
工程选型建议:全新项目优先采用 ES Modules,与语言标准及现代前端工具链一致并享受静态分析与 Tree Shaking 优势;存量 CommonJS 项目若无迁移诉求可继续沿用,需引入仅提供 ESM 的新依赖时则可通过动态 `import()`、Node.js v24 `require(esm)` 或按 `.mjs`/`.cjs` 分文件渐进过渡。
CommonJS 与 ES Module 基础规范对照
| 模块系统 | 规范定位 | 文件扩展名/配置 | 导入方式 | 导出方式 |
| CommonJS | Node.js 早期社区模块规范 | .js(默认)或显式 .cjs | require() | module.exports / exports |
| ES Module (ESM) | ECMAScript 语言官方标准 | .mjs 或 package.json 配置 "type": "module" | import / 动态 import() | export / export default |
CommonJS 与 ESM 核心维度对比
| 对比维度 | CommonJS | ESM |
| 语法 | require() 与 module.exports / exports | import 与 export / export default(默认严格模式) |
| 加载机制 | 运行时同步加载,支持条件分支动态调用 | 编译期静态分析依赖、异步模块图加载(支持顶层 await) |
| 默认支持 | Node.js 传统默认格式(无 type:module 时) | 需 .mjs 后缀或 package.json 声明 "type": "module" |
| 适合场景 | 历史服务端脚本与既有 CJS 生态项目 | 新建全栈/前后端项目与支持 Tree Shaking 的现代工具链 |
| 是否可混用 | 单文件不能混写语法;Node.js v24 可同步 require 同步 ESM,含顶层 await 须用动态 import() | 单文件不能混写语法;ESM 可直接 import CJS(作为默认导出)或借 createRequire 加载 |
实测 CJS 导出解构缓存、ESM 具名/默认/命名空间严格模式、ESM 导入 CJS、CJS 动态 import 及 Node v24 require(esm)
展开查看收起
import fsp from 'node:fs/promises';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
function deepEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mbsky-node-cjsesm-'));
try {
const req = createRequire(path.join(tmpDir, 'app.cjs'));
// Case 1: CommonJS exports (module.exports & exports), destructuring, runtime conditional require & cache
await fsp.writeFile(
path.join(tmpDir, 'math.cjs'),
`function add(a, b) { return a + b; }\nmodule.exports = { add };\n`,
'utf8',
);
await fsp.writeFile(
path.join(tmpDir, 'user.cjs'),
`exports.name = 'Alice';\nexports.age = 30;\nexports.sayHello = () => 'Hello, my name is Alice.';\n`,
'utf8',
);
const mathCjs = req('./math.cjs');
const { name, age, sayHello } = req('./user.cjs');
const conditionalLoaded = true ? req('./math.cjs') : null;
const actual1 = {
sum: mathCjs.add(2, 3),
user: { name, age, greeting: sayHello() },
cacheHit: conditionalLoaded === mathCjs,
};
const expected1 = {
sum: 5,
user: { name: 'Alice', age: 30, greeting: 'Hello, my name is Alice.' },
cacheHit: true,
};
// Case 2: ESM named exports, default export, namespace import & default strict mode
const mathEsmPath = path.join(tmpDir, 'math.mjs');
await fsp.writeFile(
mathEsmPath,
`export function add(a, b) { return a + b; }\nexport default function multiply(a, b) { return a * b; }\n`,
'utf8',
);
const userEsmPath = path.join(tmpDir, 'user.mjs');
await fsp.writeFile(
userEsmPath,
`export const name = 'Bob';
export const age = 25;
export default function sayHello() { return \`Hello, my name is \${name}.\`; }
export const isStrict = (function () { return this === undefined; })();
`,
'utf8',
);
const mathNs = await import(pathToFileURL(mathEsmPath).href);
const userNs = await import(pathToFileURL(userEsmPath).href);
const actual2 = {
add: mathNs.add(2, 3),
multiply: mathNs.default(2, 3),
userName: userNs.name,
userAge: userNs.age,
userDefault: userNs.default(),
esmStrictMode: userNs.isStrict,
namespaceKeys: Object.keys(userNs).sort(),
};
const expected2 = {
add: 5,
multiply: 6,
userName: 'Bob',
userAge: 25,
userDefault: 'Hello, my name is Bob.',
esmStrictMode: true,
namespaceKeys: ['age', 'default', 'isStrict', 'name'],
};
// Case 3: Interop — ESM importing CommonJS module (exposed via default export)
const cjsInteropPath = path.join(tmpDir, 'commonjs_module.cjs');
await fsp.writeFile(
cjsInteropPath,
`module.exports = { data: 'hello', count: 3 };\n`,
'utf8',
);
const importedCjs = await import(pathToFileURL(cjsInteropPath).href);
const actual3 = {
defaultData: importedCjs.default.data,
defaultCount: importedCjs.default.count,
hasDefaultExport: typeof importedCjs.default === 'object',
};
const expected3 = {
defaultData: 'hello',
defaultCount: 3,
hasDefaultExport: true,
};
// Case 4: Interop — CommonJS loading ESM via dynamic import()
const cjsDynamicLoaderPath = path.join(tmpDir, 'cjs_loads_esm.cjs');
const userEsmUrl = pathToFileURL(userEsmPath).href;
await fsp.writeFile(
cjsDynamicLoaderPath,
`module.exports = async function loadESM() {
const mod = await import(${JSON.stringify(userEsmUrl)});
return { name: mod.name, greeting: mod.default() };
};\n`,
'utf8',
);
const loadEsmFromCjs = req('./cjs_loads_esm.cjs');
const actual4 = await loadEsmFromCjs();
const expected4 = { name: 'Bob', greeting: 'Hello, my name is Bob.' };
// Case 5: Node.js v24 native require(esm) interoperability (sync ESM works; top-level await throws ERR_REQUIRE_ASYNC_MODULE)
const syncEsmViaRequire = req(userEsmPath);
const asyncEsmPath = path.join(tmpDir, 'tla_module.mjs');
await fsp.writeFile(asyncEsmPath, `export const v = await Promise.resolve(99);\n`, 'utf8');
let tlaErrCode = null;
try {
req(asyncEsmPath);
} catch (err) {
tlaErrCode = err.code;
}
const actual5 = {
syncRequireEsmName: syncEsmViaRequire.name,
syncRequireEsmDefault: syncEsmViaRequire.default(),
tlaRequireErrCode: tlaErrCode,
};
const expected5 = {
syncRequireEsmName: 'Bob',
syncRequireEsmDefault: 'Hello, my name is Bob.',
tlaRequireErrCode: 'ERR_REQUIRE_ASYNC_MODULE',
};
const cases = [
{ name: 'cjs_exports_and_destructuring', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
{ name: 'esm_named_default_namespace', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
{ name: 'esm_imports_cjs_interop', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
{ name: 'cjs_loads_esm_dynamic_import', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
{ name: 'node24_require_esm_sync_interop', passed: deepEqual(actual5, expected5), expected: expected5, actual: actual5 },
];
console.log(JSON.stringify({ version: process.version, cases }));
} finally {
await fsp.rm(tmpDir, { recursive: true, force: true });
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不含顶层 `await` 的同步 ES 模块在 Node.js v24 中既可用动态 `await import()` 也可直接同步 `require()`;若目标 ES 模块包含顶层 `await`,同步 `require()` 会抛出 `ERR_REQUIRE_ASYNC_MODULE`,此时必须改用异步的 `await import()`。