在 node.js 中,每一個文件都有一個模塊。 模塊間相互聯繫就必須暴露出變量、函數、或對象。
暴露:module.exports 或 exports
依賴:require()
網上講 module.exports
和 exports
的文章特別多,寫下本文是爲了做個筆記。
require()的返回值是module.exports這個對象
它是看不到exports對象的
node.js 會爲每個模塊(文件) 加入如下代碼:
module.exports = exports = {};
//...
exports
只是 module.exports
的引用。舉個不太恰當的例子: module.exports
是公司 exports
是程序員(你)公司太小 你忍忍。
module.exports = exports = {};
exports.c = //...
exports.java = //...
exports.ruby = //...
exports.node = //...
你寫出來的無論是 c 、java、ruby或node 都是公司的 公司都有權使用
如果你有一天不寫程序了,公司就生氣了:你今後再寫程序我也不要了
module.exports = exports = {};
exports.c = //...
exports.java = //...
exports.ruby = //...
exports.node = //...
exports=//... 你變了
exports.php = //... 你寫出的東西公司不要了
現在這時候,你之前寫的東西公司還是會用的,自從你變了之後,公司就不敢用你的程序了,公司要另請高人了。
module.exports = exports = {};
exports.c = //...
exports.java = //...
exports.ruby = //...
exports.node = //...
exports=//... 你變了
exports.php = //... 你寫出的東西公司不要了
module.exports = //... 完了,公司把唯一的程序員換了,你之前寫的那些垃圾公司都不要了
那麼我們何時使用 exports
何時使用 module.exports
呢?
To add functions and objects to the root of your module, you can add them to the special exports object.
If you want the root of your module’s export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.
什麼意思呢?
如果你的模塊希望暴露一些方法和對象給別人使用,就把這些加到
exports
屬性中
如果你的模塊就希望暴露一個方法比如構造函數 或一個完整的對象 就賦值給module.exports
總結:你愛怎麼用就怎麼用,別直接對 exports
賦值就行。