模块简介
在nodejs模块系统中,每个文件都可以看做单独的模块,模块通过向module.exports对象添加属性来导出,或者将module.exports指向新的对象或函数来导出。通常我们会向exports添加属性来导出,其实exports是指向module.exports的一个方便书写的变量,nodejs最后导出的是module.exports。
模块通过向module.exports对象添加属性来导出的例子:
foo.js:
const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
circle.js:
const { PI } = Math;
exports.area = (r) => PI * r ** 2;
exports.circumference = (r) => 2 * PI * r;
circle.js模块导出了area函数和circumference函数,foo.js引用了circle.js模块,将circle.js模块赋值给circle变量,此时circle变量便指向了circle.js的module.exports对象,便能使用该对象上的area函数和circumference函数。
将module.exports指向新的对象或函数来导出的例子:
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);
square.js
module.exports = class Square {
constructor(width) {
this.width = width;
}
area() {
return this.width ** 2;
}
};
这里不能将class Square赋值给exports,因为nodejs最终导出的对象是module.exports,如果赋值给exports只是改变了exports变量的指向,module.exports还是指向原对象。