代碼中,模塊是很常見的.什么是模塊,模塊就是將文件中相關(guān)的代碼封裝成一個(gè)代碼塊,以方便于在程序的其他地方調(diào)用,減少代碼的冗余.在node中,導(dǎo)出模塊主要有兩種形勢(shì),module.exports和exports常持愦粒混淆,故寫下來加深印象.
假如有配置文件,config.js.
let config = { port : 3333, name : 'wuyingming', sayhi : function(name){ console.log('hi '+ name); }}; module.exports = config;
在app.js中引入config.js
let config = require('./config'); console.log(config);
結(jié)果是:
Paste_Image.png
假如配置文件中config.js的module.exports 改成exports.config 即 :
let config = { port : 3333, name : 'wuyingming', sayhi : function(name){ console.log('hi '+ name); }}; exports.test = config;
那運(yùn)行結(jié)果為
Paste_Image.png
觀察上面的結(jié)果,我們發(fā)現(xiàn),module.exports 是原樣引用,而exports則是引用module.exports的值.
exports = module.exports;