代码中,模块是很常见的.什么是模块,模块就是将文件中相关的代码封装成一个代码块,以方便于在程序的其他地方调用,减少代码的冗余.在node中,导出模块主要有两种形势,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);
结果是:
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;
那运行结果为
Paste_Image.png
观察上面的结果,我们发现,module.exports 是原样引用,而exports则是引用module.exports的值.
exports = module.exports;