文章内容

2025/3/31 20:36:20,作 者: 黄兵

CommonJS 语法与ES Module 语法有什么区别

CommonJS 和 ES Module(ESM)是两种不同的 JavaScript 模块系统,主要区别如下:


1. CommonJS(CJS)

CommonJS 主要用于 Node.js,在浏览器端原生不支持,需要使用 Webpack、Browserify 等工具进行打包。

特点

  • 同步加载require() 是同步的)

  • 适用于服务器端(Node.js)

  • 不支持 tree shaking(代码优化)

  • 所有模块都被加载到一个单独的作用域中

  • 只能导出对象,不能直接导出变量

语法

导出

// utils.js (CommonJS)
function add(a, b) {
    return a + b;
}

module.exports = { add };

导入

// app.js (CommonJS)
const utils = require('./utils');
console.log(utils.add(2, 3)); // 输出 5

或者使用解构:

const { add } = require('./utils');
console.log(add(2, 3)); // 输出 5

2. ES Module(ESM)

ES Module 是 ECMAScript 2015 (ES6) 标准化的模块系统,现在浏览器和 Node.js 都支持 ESM。

特点

  • 异步加载(适用于浏览器)

  • 可以用于前端和后端(Node.js 14+ 原生支持 import

  • 支持 tree shaking(优化未使用的代码,提高性能)

  • 模块具有独立的作用域

  • 支持 import 直接导入变量

语法

导出

// utils.js (ESM)
export function add(a, b) {
    return a + b;
}

导入

// app.js (ESM)
import { add } from './utils.js';
console.log(add(2, 3)); // 输出 5

也可以使用 默认导出

// utils.js
export default function add(a, b) {
    return a + b;
}
// app.js
import add from './utils.js';
console.log(add(2, 3)); // 输出 5

3. CommonJS vs ES Module 对比

对比项 CommonJS(CJS) ES Module(ESM)
加载方式 同步加载(require() 异步加载(import
适用场景 服务器端(Node.js) 服务器端 & 浏览器端(ES6+)
作用域 共享作用域,会影响全局 模块作用域,独立作用域
导出方式 module.exports = {}exports.xxx = xxx export / export default
导入方式 require() import {}
Tree Shaking ❌ 不支持 ✅ 支持
默认支持的环境 Node.js 浏览器 & Node.js 14+

4. 什么时候用 CommonJS,什么时候用 ES Module?

情况 推荐使用
Node.js 开发 CommonJS(默认支持)
浏览器开发 ES Module
Webpack/Parcel/Vite ES Module(支持 tree shaking)
希望代码更现代化 ES Module
兼容旧版 Node.js CommonJS

5. Node.js 如何使用 ES Module?

package.json 中添加:

{
  "type": "module"
}

然后就可以使用 import 了:

import { add } from './utils.js';

如果不加 "type": "module",就必须使用 CommonJS 语法 (require())。


总结

CommonJS(CJS)适用于 Node.js,使用 require()
ES Module(ESM)适用于现代 JavaScript,使用 importexport
ESM 更现代化,支持 tree shaking,适用于前端
Node.js 14+ 也可以使用 ESM
浏览器端必须使用 ES Module

如果你的项目主要运行在 Node.js(比如后端 API),可以继续使用 CommonJS。如果是前端项目,推荐使用 ES Module,因为它更现代化,并且支持 Tree Shaking。 🚀

分享到:

发表评论

评论列表