module.export和export有什么区别

2024-02-21

有什么区别module.export and export

如果 module.export 对象中有一些属性怎么办? 将要export.xx那么无效吗?


首先它是exports and module.exports并不是export and module.export(还有一个exportJavaScript 中的关键字,但 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

module.export和export有什么区别 的相关文章

随机推荐