关于这个问题NodeJS的官方文档中有一句很精辟的解释:
What’s the difference between module.exports and exports?
The first exposes the object it points to. The latter exposes the properties of the object it points to.
翻译过来就是说,module.exports是直接导出整个对象,而exports导出的是对象中的属性。以下通过两个简单的例子可以直观的看清楚这两种方式的区别。
module.exports
这种方式最好理解,直接导出一个对象,如下所示:
// item.js
const car = {
brand: 'Ford',
model: 'Fiesta'
}
module.exports = car
// app.js
const item = require('./item')
console.log(item)
// output
D:\workspace\idea\nodejs_demo>node app.js
{ brand: 'Ford', model: 'Fiesta' }
可以看到require进来的就是module.exports导出的对象。
exports
这种方式导出的对象会成为最终导出的对象的一个属性,如下:
// items.js
const car = {
brand: 'Ford',
model: 'Fiesta'
}
const computer = {
brand: 'Dell',
model: 'OptiPlex'
}
exports.car = car // 成为导出对象的car属性
exports.computer = computer // 成为导出对象的computer属性
// app.js
const items = require('./items')
console.log(items)
// output
D:\workspace\idea\nodejs_demo>node app.js
{
car: { brand: 'Ford', model: 'Fiesta' },
computer: { brand: 'Dell', model: 'OptiPlex' }
}
可以发现,exports.car = car
导出的car对象实际上成为了导出对象的car属性,exports.computer = computer
导出的computer对象成为了导出对象的computer属性。
此时回过头来看下面这两句话应该就能体会到这两种方式的本质区别了:
What’s the difference between module.exports and exports?
The first exposes the object it points to. The latter exposes the properties of the object it points to.
原话出自NodeJS官方文档: https://nodejs.dev/learn/expose-functionality-from-a-nodejs-file-using-exports