首先它是exports
and module.exports
并不是export
and module.export
(还有一个export
JavaScript 中的关键字,但 Node 尚不支持)。
每个 Node 模块都包含以下函数:
(function (exports, require, module, __filename, __dirname) {
// Your module code actually lives in here
});
See: https://nodejs.org/api/modules.html#modules_the_module_wrapper https://nodejs.org/api/modules.html#modules_the_module_wrapper
您的模块不会像某些人想象的那样返回该函数导出的对象。它只能通过以下方式将数据传递给调用者向提供的参数添加属性.
module.exports
and exports
are 最初是同一个对象- 但它是module.exports
那是实际出口如果它们最终不是同一个对象。
这意味着这将起到相同的作用:
module.exports.x = 1;
# or:
exports.x = 1;
因为它改变了同一个物体.
但是这个will not是相同的:
module.exports = {x: 1};
as this:
exports = {x: 1};
最后一张将不出口 the x
因为它会代替中的对象exports
(原来是the same对象为module.exports
)同时保留默认的空对象module.exports
才能实际导出。
The module.exports = {x: 1};
也替代一个新对象,但它将它放置在实际导出所需的位置。注意这个指令changes the property
of the module
对象,在模块包装的隐式函数返回后,调用者可以看到该对象。
现在这可以工作了:
exports = {x: 1};
module.exports = exports;
因为它替换了中的对象exports
与一个新的,但它也把它放入module.exports
.
请记住,它始终是module.exports
如果您没有用新对象替换其中一个,那么最后很重要,那么您可以在设置它们的属性时互换使用它们:
exports.x = 1;
module.exports.y = 2;
有关更多信息,请参阅此答案:
- 为什么我们在nodejs中使用导出? https://stackoverflow.com/questions/41280537/why-we-use-exports-in-nodejs/41281525#41281525