ES6模块与CommonJS本质不同:ES6是编译时静态加载、顶层导入、活绑定导出;CommonJS是运行时动态加载、任意位置require、值拷贝导出;混用易致ReferenceError或空模块。

ES6 模块(import/export)和 CommonJS(require/module.exports)不是简单“换种写法”的关系,它们在加载时机、导出行为、运行环境和循环引用处理上根本不同。直接混用或盲目替换会触发 ReferenceError、TypeError: Cannot assign to read only property 'exports' 或打包后模块为空。
ES6 模块是编译时静态分析的,CommonJS 是运行时动态执行的
这是最核心区别。ES6 的 import 必须写在顶层作用域,不能放在 if 或函数里;而 require 可以随时调用,甚至拼接路径:
import { foo } from './utils.js'; // ✅ 合法:静态语句
if (condition) {
import('./lazy.js'); // ✅ 动态 import() 是 Promise,但仍是语法层面支持
}
// ❌ 错误:ES6 不允许
if (condition) {
import { bar } from './cond.js';
}
CommonJS 则完全自由:
if (process.env.NODE_ENV === 'dev') {
const debug = require('./debug');
debug.init();
}
这意味着:Babel 或 TypeScript 编译 ES6 模块时,能提前报错未定义的导入;而 CommonJS 的错误(比如 require('missing'))只有运行到那行才暴露。
立即学习“Java免费学习笔记(深入)”;
export default 和 module.exports 表面相似,实际语义不同
export default 导出的是一个“默认绑定”,它不等于“导出一个叫 default 的属性”;而 module.exports = xxx 是直接赋值整个模块对象。
- ES6 中
export default function foo(){}等价于export { foo as default },但导入时import foo from './x'得到的是函数本身,不是{ default: fn } - CommonJS 中
module.exports = function foo(){},在 ESM 中通过import foo from './x'也能拿到函数——这是 Node.js 的互操作层做的适配,不是语言规范行为 - 但若写
exports.default = fn(没动module.exports),ESM 的import x from就拿不到东西,因为 Node.js 只把module.exports整体映射为默认导出
更危险的是命名导出:export const a = 1, b = 2 在 CommonJS 中无法用 require() 原生读取,必须靠工具(如 createRequire)或转译。
Node.js 中混合使用必须明确设置 "type": "module" 或用 .mjs
Node.js 默认把 .js 当作 CommonJS。即使你写了 import,也会报错 Cannot use import statement outside a module。
- 方案一:在
package.json加"type": "module"→ 整个包所有.js都按 ESM 解析 - 方案二:用
.mjs后缀 → 该文件强制 ESM,不管type设置 - 方案三:用
createRequire(import.meta.url)在 ESM 文件里安全调用 CommonJS 模块
反向(ESM 中 require)不被允许,也不能直接 import 一个纯 CommonJS 文件(如 lodash)并解构其命名导出——它只有默认导出,且内部无 export 语句。
循环依赖时,ES6 模块返回“活绑定”,CommonJS 返回“值拷贝”
假设有 A.js 和 B.js 相互 import 或 require:
// A.js (ESM)
import { bValue } from './B.js';
export let aValue = 1;
console.log(bValue); // undefined(B 还没执行完)
setTimeout(() => console.log(bValue), 0); // 2 → 活绑定,随 B 更新
// B.js (ESM)
import { aValue } from './A.js';
export let bValue = 2;
console.log(aValue); // undefined(A 还没执行完)
而 CommonJS:
// A.js (CJS)
const b = require('./B.js');
console.log(b.value); // undefined(B.exports 还是空对象)
exports.value = 1;
// B.js (CJS)
const a = require('./A.js');
console.log(a.value); // undefined
exports.value = 2;
结果都是 undefined,但 ESM 的后续读取能看到更新,CJS 的 require 结果永远是首次执行完那一刻的 module.exports 快照。
真正容易踩坑的是跨环境:Webpack/Vite 默认按 ESM 处理,但你在 node_modules 里引入一个只写了 module.exports 的库,又试图 import { x } from 'lib' —— 它大概率失败,除非库同时提供了 exports 字段或 types 声明。











