CommonJS 模块


稳定性: 2 - 稳定

在 Node.js 模块系统中,每个文件都被视为独立的模块。 例如,假设一个名为 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

以下是 circle.js 的内容:

const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;

模块 circle.js 已导出函数 area()circumference()。 通过在特殊的 exports 对象上指定额外的属性,将函数和对象添加到模块的根部。

模块的本地变量将是私有的,因为模块被 Node.js 封装在函数中(参见模块封装器)。 在此示例中,变量 PIcircle.js 私有的。

可以为 module.exports 属性分配新的值(例如函数或对象)。

下面,bar.js 使用了导出 Square 类的 square 模块:

const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);

square 模块在 square.js 中定义:

// 赋值给 exports 不会修改模块,必须使用 module.exports
module.exports = class Square {
  constructor(width) {
    this.width = width;
  }

  area() {
    return this.width ** 2;
  }
};

模块系统在 require('module') 模块中实现。

Stability: 2 - Stable

In the Node.js module system, 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)}`);

On the first line, foo.js loads the module circle.js that is in the same directory as foo.js.

Here are the contents of circle.js:

const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;

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.

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.

The module.exports property can be assigned a new value (such as a function or object).

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()}`);

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;
  }
};

The module system is implemented in the require('module') module.