我在Node.js模块中找到了以下契约:

module.exports = exports = nano = function database_module(cfg) {...}

我想知道module.exports和exports之间有什么区别,为什么在这里使用它们。


当前回答

“如果您希望模块导出的根是一个函数(例如构造函数),或者如果您希望在一个赋值中导出一个完整的对象,而不是一次生成一个属性,请将其分配给module.exports而不是导出。”-http://nodejs.org/api/modules.html

其他回答

最初,module.exports=导出,require函数返回module.exports引用的对象。

如果我们向对象添加属性,比如exports.a=1,那么module.exports和exports仍然引用同一个对象。因此,如果我们调用require并将模块分配给变量,那么该变量具有属性a,其值为1;

但是如果我们重写其中一个,例如exports=function(){},那么它们现在就不同了:exports引用新对象,module.exports引用原始对象。如果我们需要该文件,它将不会返回新对象,因为module.exports不引用新对象。

对我来说,我将继续添加新属性,或者将它们都覆盖到新对象中。只是忽略一个是不正确的。请记住,module.exports才是真正的老板。

为什么这两个都用在这里

我相信他们只是想清楚module.exports、exports和nano指向同一个函数——允许您使用任意一个变量来调用文件中的函数。nano为函数的功能提供了一些上下文。

导出不会被导出(只有module.exports会被导出),那么为什么还要麻烦覆盖它呢?

冗长的权衡限制了未来错误的风险,例如在文件中使用导出而不是module.exports。它还澄清了module.exports和exports实际上指向相同的值。


module.exports与导出

只要不重新分配module.exports或exports(而是向它们都引用的对象添加值),就不会有任何问题,并且可以安全地使用exports以更简洁。

当将其中一个分配给非对象时,它们现在指向不同的位置,这可能会令人困惑,除非您有意希望module.exports是特定的(例如函数)。

将导出设置为非对象没有多大意义,因为必须在末尾设置module.exports=导出,才能在其他文件中使用它。

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

exports.msg = 'hi';
console.log(module.exports === exports); // true

exports = 'yo';
console.log(module.exports === exports); // false

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

module.exports = 'hello';
console.log(module.exports === exports); // false

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

为什么将module.exports分配给函数?

更简洁!比较第二个示例的长度:

helloWorld1.js: module.exports.hello = () => console.log('hello world');

app1.js:let sayHello=require('./helloWorld1');sayHellohello;//你好,世界

helloWorld2.js: module.exports = () => console.log('hello world');

app2.js:let sayHello=require('./helloWorld2');说你好;//你好,世界

JavaScript通过引用的副本传递对象

这与JavaScript中通过引用传递对象的方式有细微差别。

exports和module.exports都指向同一个对象。exports是变量,module.exports是模块对象的属性。

假设我写了这样的东西:

exports = {a:1};
module.exports = {b:12};

exports和module.exports现在指向不同的对象。修改导出不再修改module.exports。

当import函数检查module.exports时,它得到{b:12}

您创建的每个文件都是一个模块。模块是一个对象。它具有名为exports:{}的属性,默认情况下该属性为空对象。

您可以创建函数/中间件并将其添加到这个空的导出对象中,例如exports.findById()=>{…},然后在应用程序中的任何位置使用。。。

控制器/user.js

exports.findById = () => {
    //  do something
}

需要在routes.js中使用:

const {findyId} = './controllers/user'

exports和module.exports是相同的,除非在模块内重新分配导出。

考虑这一点最简单的方法是认为这一行隐式地位于每个模块的顶部。

var exports = module.exports = {};

如果在模块内重新分配导出,则在模块内将其重新分配,并且不再等于module.exports。这就是为什么,如果要导出函数,必须执行以下操作:

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

如果只将函数(){…}分配给导出,则将导出重新分配为不再指向module.exports。

如果您不想每次通过module.exports引用函数,可以执行以下操作:

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

注意,module.exports是最左边的参数。

将财产附加到导出不一样,因为您不需要重新分配它。这就是为什么可以这样做的原因

exports.foo = function() { ... }