登录
首页 >  文章 >  前端

ES6模块与CommonJS对比解析

时间:2026-02-12 10:48:41 213浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《ES6模块与CommonJS区别详解》,正文内容主要涉及到等等,如果你正在学习文章,或者是对文章有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

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

javascript如何进行模块化_es6模块和commonjs有什么区别【教程】

ES6 模块(import/export)和 CommonJS(require/module.exports)不是简单“换种写法”的关系,它们在加载时机、导出行为、运行环境和循环引用处理上根本不同。直接混用或盲目替换会触发 ReferenceErrorTypeError: 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'))只有运行到那行才暴露。

export defaultmodule.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 相互 importrequire

// 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 声明。

终于介绍完啦!小伙伴们,这篇关于《ES6模块与CommonJS对比解析》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>