返回

译码 ES6 模块和 CommonJS 之间的区别

前端

ES6 模块和 CommonJS 模块都是 JavaScript 模块系统,用于组织和重用代码。然而,它们在语法、加载机制和作用域规则等方面存在着一些关键差异。

语法

ES6 模块使用 exportimport 来定义和导入模块,而 CommonJS 模块使用 require() 函数。

ES6 模块:

// a.js
export const message = "Hello, world!";

// b.js
import { message } from "./a.js";

console.log(message); // 输出: "Hello, world!"

CommonJS 模块:

// a.js
exports.message = "Hello, world!";

// b.js
const message = require("./a.js").message;

console.log(message); // 输出: "Hello, world!"

加载机制

ES6 模块使用浏览器或 Node.js 的原生模块加载器加载,而 CommonJS 模块使用 CommonJS 规范的模块加载器加载。

ES6 模块:

<script type="module" src="./a.js"></script>
<script type="module" src="./b.js"></script>
// a.js
export const message = "Hello, world!";

// b.js
import { message } from "./a.js";

console.log(message); // 输出: "Hello, world!"

CommonJS 模块:

// a.js
exports.message = "Hello, world!";

// b.js
const message = require("./a.js").message;

console.log(message); // 输出: "Hello, world!"

作用域规则

ES6 模块中的变量和函数在模块的作用域内是私有的,而 CommonJS 模块中的变量和函数在模块的作用域内是全局的。

ES6 模块:

// a.js
let message = "Hello, world!";

// b.js
import { message } from "./a.js";

console.log(message); // 输出: "Hello, world!"

CommonJS 模块:

// a.js
var message = "Hello, world!";

// b.js
const message = require("./a.js").message;

console.log(message); // 输出: "Hello, world!"

在 CommonJS 模块中,message 变量在 a.jsb.js 中都是全局变量,因此可以在这两个文件中访问。而在 ES6 模块中,message 变量在 a.js 中是私有变量,在 b.js 中是不可访问的。

总结

ES6 模块和 CommonJS 模块都是 JavaScript 模块系统,用于组织和重用代码。然而,它们在语法、加载机制和作用域规则等方面存在着一些关键差异。

特性 ES6 模块 CommonJS 模块
语法 exportimport 关键字 require() 函数
加载机制 浏览器或 Node.js 的原生模块加载器 CommonJS 规范的模块加载器
作用域规则 变量和函数在模块的作用域内是私有的 变量和函数在模块的作用域内是全局的

在选择使用哪种模块系统时,您需要考虑项目的需求和偏好。如果您需要一个现代、模块化的 JavaScript 模块系统,那么 ES6 模块是一个不错的选择。如果您需要一个兼容旧版 JavaScript 代码的模块系统,那么 CommonJS 模块是一个不错的选择。