在这个页面(http://docs.nodejitsu.com/articles/getting-started/what-is-require)上,它声明“如果你想将exports对象设置为一个函数或一个新对象,你必须使用模块。出口对象。”

我的问题是为什么。

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

我的控制台。记录结果(result=require(example.js)),第一个是[Function],第二个是{}。

你能解释一下背后的原因吗?我读了这篇文章:模块。出口vs Node.js中的出口。它是有帮助的,但并没有解释为什么它是这样设计的。如果直接退回出口的参考资料会有问题吗?


当前回答

Node是这样做的:

module.exports = exports = {}

模块。Exports和Exports引用同一个对象。

这样做只是为了方便。 所以不像这样写

module.exports.PI = 3.14

我们可以写

exports.PI = 3.14

因此,向exports添加属性是可以的,但将其分配给不同的对象是不可以的

exports.add = function(){
.
.
} 

这是可以的,和module.exports.add = function(){…}一样

exports = function(){
.
.
} 

这是不正确的,并且空对象将作为模块返回。Exports仍然引用{},Exports引用不同的对象。

其他回答

module是一个带有exports属性的纯JavaScript对象。exports是一个简单的JavaScript变量,它被设置为module.exports。 在文件的末尾,node.js基本上会'return'模块。导出到require函数。在Node中查看JS文件的简化方法如下:

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

// your code

return module.exports;

如果你在导出上设置一个属性,比如export。a = 9;,这也会设置module.exports.a,因为在JavaScript中对象是作为引用传递的,这意味着如果你将多个变量设置为同一个对象,它们都是同一个对象;然后是exports和module。导出也是相同的对象。 但是如果你将exports设置为新的内容,它将不再被设置为module。导出,导出和模块。出口不再是同一个对象。

Rene回答了导出和模块之间的关系。Exports非常清楚,它都是关于javascript引用的。我只想补充一点:

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

Var app = exports = module。Exports = {};

这将确保即使我们改变了模块。导出,我们仍然可以通过使这两个变量指向同一个对象来使用导出。

模块之间有两个区别。出口和出口

当将单个类、变量或函数从一个模块导出到另一个模块时,我们使用module.exports。但是导出到多个变量或函数,从一个模块到另一个模块,我们使用导出。 模块。Exports是require()调用返回的对象引用。但是require()不会返回exports。

>>链接示例查看更多细节

上面所有的答案都解释得很好,我想补充一些我今天面临的问题。

当你使用exports导出东西时,你必须使用variable。就像,

File1.js

exports.a = 5;

在另一个文件中

File2.js

const A = require("./File1.js");
console.log(A.a);

使用module.exports

File1.js

module.exports.a = 5;

在File2.js

const A = require("./File1.js");
console.log(A.a);

默认module.exports

File1.js

module.exports = 5;

在File2.js

const A = require("./File2.js");
console.log(A);

myTest.js

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

exports.put = function () {};

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

导出和模块。导出是相同的,并且是对同一对象的引用。您可以根据自己的方便通过两种方式添加属性。