模块:CommonJS 模块
【Modules: CommonJS modules】
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 类:
【Below, 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.】