在这个页面(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中的出口。它是有帮助的,但并没有解释为什么它是这样设计的。如果直接退回出口的参考资料会有问题吗?


当前回答

myTest.js

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

exports.put = function () {};

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

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

其他回答

还有一件事可能有助于理解:

math.js

this.add = function (a, b) {
    return a + b;
};

client.js

var math = require('./math');
console.log(math.add(2,2); // 4;

很好,在这种情况下:

console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true

因此,默认情况下,"this"实际上等于module.exports。

但是,如果您将实现更改为:

math.js

var add = function (a, b) {
    return a + b;
};

module.exports = {
    add: add
};

在这种情况下,它可以正常工作,但是,“this”不等于module。不再导出,因为创建了一个新对象。

console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false

现在,require返回的是模块中定义的东西。出口,不再是这个或出口。

另一种方法是:

math.js

module.exports.add = function (a, b) {
    return a + b;
};

Or:

math.js

exports.add = function (a, b) {
    return a + b;
};

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

当你使用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);

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

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

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

您可以将导出视为模块的快捷方式。在 给定的模块。事实上,exports只是一个变量 初始化为module的值。在模块之前导出 评估。该值是一个对象的引用(在 这种情况下)。这意味着exports保存了对该对象的引用 由module.exports引用的对象。它还意味着通过赋值 exports的另一个值不再绑定到module.exports。

MDN的这个解释对我来说是最清楚的。

基本上,内存中只有一个对象,由两个变量(exports和module.exports)引用。

exports.a = 23

=

module.exports = {a:23}

But,

exports = {a:23}

不等于

module.exports = {a:23}

当你直接将一个新对象赋值给exports变量时,该变量不会引用module。出口了。

myTest.js

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

exports.put = function () {};

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

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