Node.js中Moudle.export与export的区别

背景

在使用Node.js做一些小案例的时候,需要js文件导出一个可实例化的对象的函数,发现使用moudle.export可以导出类,而我又想使用export可不可以导出一个类呢.很可惜,结果是并不能使用export导出一个类.
所以,moudle.exportexport的区别是什么呢.

阅读以下文章需要了解变量的赋值以及对象的引用之间的区别.

解释

module is a plain JavaScript object with an exports property. exports is a plain JavaScript variable that happens to be set to module.exports. At the end of your file, node.js will basically 'return' module.exports to the require function. A simplified way to view a JS file in Node could be this:

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

// your code

return module.exports;

If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so then exports and module.exports are the same object.
But if you set exports to something new, it will no longer be set to module.exports, so exports and module.exports are no longer the same object.

以上是我找到的一段解释.它出自Difference between “module.exports” and “exports” in the CommonJs Module System

以下是我的理解:

module可以理解为一个带有exports property的Object( typeof Module.exports == Object).

exports是指向于module.exports的变量.

请看下面的代码的输出情况:

// input.js

module.exports.outPutFn = function(){
    console.log("Echo:Hi");
}
exports.outLiteral=":)";
console.log(module);
console.log(exports);

结果为:


而使用require的js文件,实际上引入的是module.exports,而非exports(在手动修改exports变量指向的时候,比如说 exports = "new".这个时候exports就不会再去指向module,exports对象.这个时候exports就会失效.这就理解了为什么使用 exports = Fn,而另一个js文件不能如愿接收此函数的情况.)
代码如下:

// out.js
module.exports = "I'm a lucky module :}";
exports = ":<";
// input.js
let Inputmodule = require('./out.js');
console.log(Inputmodule);

结果为 :

同样的,在一些代码里会看到类似于下面的代码.如果对两者已经理解的话,那么下面的代码也会理解 : 这么做是为了保持exports与module.exports一致

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



参考

原文地址:https://www.cnblogs.com/gtscool/p/13203614.html