你搞懂module.exports和exports了吗?

为了更好的理解 module.exports 和 exports 的关系,我们先来巩固下 js 的基础:

// test.js
var a = {name: 1};
var b = a;
console.log(a);  // { name: 1 }
console.log(b);  // { name: 1 }
 
b.name = 2;
console.log(a);  // { name: 2 }
console.log(b);  // { name: 2 }
 
var b = {name: 3};
console.log(a);  // { name: 2 }
console.log(b);  // { name: 3 }

a 是一个对象,b 是对 a 的引用,即 a 和 b 指向同一块内存,所以前两个输出一样。当对 b 作修改时,即 a 和 b 指向同一块内存地址的内容发生了改变,所以 a 也会体现出来,所以第三四个输出一样。当 b 被覆盖时,b 指向了一块新的内存,a 还是指向原来的内存,所以最后两个输出不一样。
明白了上述例子后,我们只需知道三点就知道 exports 和 module.exports 的区别了:

  • module.exports 初始值为一个空对象 {}
  • exports 是指向的 module.exports 的引用
  • require() 返回的是 module.exports 而不是 exports

我们会看到这样的写法:

exports = module.exports = xxx

上面的代码等价于:

module.exports = xxx
exports = module.exports

原理很简单,即 module.exports 指向新的对象时,exports 断开了与 module.exports 的引用,那么通过 exports = module.exports 让 exports 重新指向 module.exports 即可。
系统自动给 nodejs 文件增加2个变量 exports 和 module,module 又有一个属性 exports,这个exports 属性指向一个空对象 {},同时 exports这个变量也指向了这个空对象{},于是就有了 exports => {} <=module.exports
这2个 exports 其实是没有直接关系的,唯一的关系是他们初始都指向同一个空对象{},如果其中一个不指向做个空对象了,那么他们的关系就没有了