模块:CommonJS 模块
\Modules: CommonJS modules
\Stability: 2 - Stable
CommonJS 模块是为 Node.js 打包 JavaScript 代码的原始方式。Node.js 还支持浏览器和其他 JavaScript 运行时使用的 ECMAScript 模块 标准。
\CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes.
在 Node.js 中,每个文件都被视为一个单独的模块。例如,假设一个名为 foo.js 的文件:
\In Node.js, each file is treated as a separate module. For
example, consider a file named foo.js:
const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); 在第一行,foo.js 加载了与 foo.js 位于同一目录中的模块 circle.js。
\On the first line, foo.js loads the module circle.js that is in the same
directory as foo.js.
以下是 circle.js 的内容:
\Here are the contents of circle.js:
const { PI } = Math;
exports.area = (r) => PI * r ** 2;
exports.circumference = (r) => 2 * PI * r; 模块 circle.js 已导出函数 area() 和 circumference()。通过在特殊的 exports 对象上指定额外的属性,将函数和对象添加到模块的根部。
\The module circle.js has exported the functions area() and
circumference(). Functions and objects are added to the root of a module
by specifying additional properties on the special exports object.
模块的局部变量将是私有的,因为模块被 Node.js 封装在一个函数中(参见 模块封装器)。在此示例中,变量 PI 是 circle.js 私有的。
\Variables local to the module will be private, because the module is wrapped
in a function by Node.js (see module wrapper).
In this example, the variable PI is private to circle.js.
可以为 module.exports 属性分配新的值(例如函数或对象)。
\The module.exports property can be assigned a new value (such as a function
or object).
在以下代码中,bar.js 使用 square 模块,该模块导出 Square 类:
\In the following code, bar.js makes use of the square module, which exports
a Square class:
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`); square 模块在 square.js 中定义:
\The square module is defined in square.js:
// Assigning to exports will not modify module, must use module.exports
module.exports = class Square {
constructor(width) {
this.width = width;
}
area() {
return this.width ** 2;
}
}; CommonJS 模块系统在 module 核心模块 中实现。
\The CommonJS module system is implemented in the module core module.