由于node對es6的import支持還不完美,還得研究下es5的模塊導出機制。
其實require/exports是野生的規(guī)范,是社區(qū)擬定的規(guī)則,被CommonJS,AMD.CMD支持。CommonJS是主流。
但是我們會使用到module.exports與exports兩種導出模塊的方法,它們之間的區(qū)別呢?
基礎知識
每一個node.js執(zhí)行文件,都自動創(chuàng)建一個module對象,同時,module對象會創(chuàng)建一個叫exports的屬性,初始化的值是 {}
module.exports = {};
require是值的拷貝,不是值引用,所以不用擔心異步導致的數(shù)據(jù)污染。
區(qū)別
主要有3點:
- module.exports 初始值為一個空對象 {}
- require() 返回的是 module.exports 而不是 exports
- exports 是指向的 module.exports 的值的引用。
前兩條很好理解,第三條,意思是:
- 如果exports = newObject,那么exports斷開了與module.exports的引用,兩者就不再指向一個內存。
地址了。所有才有了如下的寫法:
exports = module.exports = somethings
等價于
module.exports = somethings
exports = module.exports
通過 exports = module.exports 讓 exports 重新指向 module.exports .
- 如果 module.exports = newObject,exports跟module.exports不再指向同一個值(或者叫內存地址),那么exports就失效了。
總結:
如果不使用module.exports,僅使用exports,那么exports只能到處屬性,不能重新賦值對象。建議使用exports.x等寫法。
如果使用了module.exports = newObject,那么這時候exports就失效了,必須使用exports = module.exports = newObject建立聯(lián)系