node.js模块导出

Way*_*rry 1 javascript commonjs node.js

这是什么原因:

exports.foo = 'foo';

var bar = require('./foo');
console.log(bar); // {foo: 'foo'}
Run Code Online (Sandbox Code Playgroud)

但这不是:

var data = { foo: 'foo' };
exports = data;

var bar = require('./foo');
console.log(bar); // {}
// expected {foo: 'foo'}
Run Code Online (Sandbox Code Playgroud)

Tam*_*mil 5

我将尝试回答这个问题作为一个JavaScript问题代码示例

function a() {}
a.prototype.foo = {test:"bar"}
var d = new a();
var c = new a();
console.log(d.prototype ==== c.prototype) // Both c and d share the same prototype object
d.foo.hai = "hello"
console.log(d.prototype ==== c.prototype) // Still the they refer to the same
d.foo = {im: "sorry"}
console.log(d.prototype ==== c.prototype) // now they don't
Run Code Online (Sandbox Code Playgroud)

节点相同

console.log(module.exports === exports);// true; They refer to the same object
exports.a = {tamil: "selvan"} 
console.log(module.exports === exports);// true even now 

exports = {sorry: "im leaving"}; // overrides modules.exports
console.log(module.exports === exports); //false now they don't
console.log(module.exports); // {a: {tamil: "selvan"}}
console.log(exports);  // {sorry: "im leaving"}
Run Code Online (Sandbox Code Playgroud)

exports和module.exports引用相同的核心对象,直到您在javsacript原型对象中重写为止.覆盖参考更改的那一刻.

module.exports = {something: "works"} 之所以有效,是因为您正在更改节点在缓存时所关心的模块的属性.

即便如此

module.exports === exports //is false they are no more the same

这证明反之亦然:)

还有一件事module是对当前模块的引用,所以总是喜欢使用module.exportsexports