CommonJs模块系统中“ module.exports”和“ exports”之间的区别

JavaScript Node.js

老丝Tony

2020-03-19

在此页面(http://docs.nodejitsu.com/articles/getting-started/what-is-require)上,声明“如果要将导出对象设置为函数或新对象,则必须使用module.exports对象。”

我的问题是为什么。

// right
module.exports = function () {
  console.log("hello world")
}
// wrong
exports = function () {
  console.log("hello world")
}

我console.logged结果(result=require(example.js))和第[Function]一个是{}

您能否解释其背后的原因?我在这里阅读了这篇文章:Node.js中的module.exports与export它很有帮助,但没有解释以这种方式设计它的原因。如果直接返回出口参考书会不会有问题?

第2372篇《CommonJs模块系统中“ module.exports”和“ exports”之间的区别》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
米亚ItachiL 2020.03.19

myTest.js

module.exports.get = function () {};

exports.put = function () {};

console.log(module.exports)
// output: { get: [Function], put: [Function] }

exports并且module.exports是相同的,并且是对同一对象的引用。您可以根据需要通过两种方式添加属性。

泡芙卡卡西神乐 2020.03.19

module是具有exports属性的普通JavaScript对象exports是一个普通的JavaScript变量,碰巧设置为module.exports在文件末尾,node.js基本上将“返回” module.exportsrequire函数。在Node中查看JS文件的一种简化方法是:

var module = { exports: {} };
var exports = module.exports;

// your code

return module.exports;

如果在上设置exports,如exports.a = 9;,该属性也会设置module.exports.a,因为对象是作为JavaScript中的引用传递的,这意味着如果将多个变量设置为同一对象,则它们都是同一对象;因此,exportsmodule.exports是相同的对象。
但是,如果你设置exports新的东西,这将不再被设定为module.exports,所以exportsmodule.exports不再是同一个对象。

Davaid樱 2020.03.19

刘若英的约之间的关系答案exportsmodule.exports是相当清楚的,它是所有关于JavaScript的引用。只需添加:

我们在许多节点模块中看到了这一点:

var app = exports = module.exports = {};

这将确保即使我们更改了module.exports,我们仍然可以通过使这两个变量指向同一对象来使用export。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android