nodejs的模块加载机制

本文介绍了Node.js中模块的两种导出方式:通过向module.exports添加属性导出及将module.exports指向新对象或函数导出。并给出了具体示例。

模块简介

在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指向新的对象或函数来导出的例子:

bar.js
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还是指向原对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值