exports与module.exports的关系和区别

一直比较纠结exports与module.exports的关系,在查阅资料后,终于有了一些清醒的认识。简单说,exports只是对module.exports对象的引用。module.exports才是真正的接口,exports只不过是它的一个辅助工具,最终返回给调用的是module.exports而不是exports。

注:通过console.log(module)我们可以看到module这个对象的属性,其中有一个属性就是exports,初始化为空对象,这里的module.exports就是这个空对象。而exports是另一个对象,它只是对module.exports的引用。

参考:http://www.cnblogs.com/pigtail/archive/2013/01/14/2859555.html
https://cnodejs.org/topic/5231a630101e574521e45ef8

要想了解为何每个文件模块中都存在require、exports、module3个变量可参考朴灵的深入浅出P19。

为了更好地理解exports与module.exports的关系,先来点js基础,示例:

var a = {name: 'fengliner 1'};
var b =a;

console.log(a);
console.log(b);

b.name = 'fengliner 2';
console.log(a);
console.log(b);

var b = {name: 'fengliner 3'};
console,log(a);
console.log(b);

保存为test.js,运行结果:

{name: 'fengliner 1'}
{name: 'fengliner 1'}
{name: 'fengliner 2'}
{name: 'fengliner 2'}
{name: 'fengliner 2'}
{name: 'fengliner 3'}

解释:a是一个对象,b是对a的引用,即a和b指向同一个对象,即a和b指向同一块内存地址,所以前两个输出一样。当对b做修改时,即a和b指向同一块内存地址的内容发生了改变,所以a也会体现出来,所以第三个第四个输出一样。当对b完全覆盖时,b就指向了一块新的内存地址(并没有对原先的内存做修改),a还是指向原来的内存块,即a和b不再指向同一块内存,也就是说此时a和b已毫无关系,所以最后两个输出不一样。

明白上述例子后,进入正题。
只需知道三点即可知道exports和module.exports的区别了:

  1. exports是指向module.exports的引用
  2. module.exports初始值为一个空对象{},所以exports初始值也是{}
  3. require()返回的是module.exports而不是exports

所以,我们通过

var name = 'fengliner';
exports.name = name;
exports.sayName = function() {
    console.log(name);
}

给exports赋值其实是给module.exports这个空对象添加了两个属性而已,上面的代码相当于:

var name = 'fengliner';
module.exports.name = name;
module.exports.sayName = function() {
    console.log(name);
}

我们通常这样使用exports和module.exports,一个简单的例子,计算圆的面积:

使用exports

app.js
var circle = require('./circle');
console.log(circle.area(4));

circle.js
exports.area = function(r) {
    return r * r * Math.PI;
}

使用module.exports

app.js
var area = require('./area');
console.log(area(4));

area.js
module.exports = function(r) {
    return r * r * Math.PI;
}

上面两个例子输出是一样的。你也许会问,为什么不这样写呢?

app.js
var area = require('./area');
console.log(area(4));

area.js
exports = function(r) {
    return r * r * Math.PI;
}

运行上面的例子会报错。这是因为,前面的例子中通过给 exports 添加属性,只是对 exports 指向的内存做了修改,而

exports = function(r) {
    return r * r * Math.PI;
}

其实是对 exports 进行了覆盖,也就是说 exports 指向了一块新的内存(内容为一个计算圆面积的函数),也就是说 exports 和 module.exports 不再指向同一块内存,也就是说此时 exports 和 module.exports 毫无联系,也就是说 module.exports 指向的那块内存并没有做任何改变,仍然为一个空对象 {} ,也就是说 area.js 导出了一个空对象,所以我们在 app.js 中调用 area(4) 会报 TypeError: object is not a function 的错误。

所以,一句话做个总结:当我们想让模块导出的是一个对象时, exports 和 module.exports 均可使用(但 exports 也不能重新覆盖为一个新的对象),而当我们想导出非对象接口时,就必须也只能覆盖 module.exports 。

我们经常看到这样的用写法:

exports = module.exports = somethings

上面的代码等价于

module.exports = somethings
exports = module.exports

原因也很简单, module.exports = somethings 是对 module.exports 进行了覆盖,此时 module.exports 和 exports 的关系断裂,module.exports 指向了新的内存块,而 exports 还是指向原来的内存块,为了让 module.exports 和 exports 还是指向同一块内存或者说指向同一个 “对象”,所以我们就 exports = module.exports 。