module.exports 和 exports 的区别

代码中,模块是很常见的.什么是模块,模块就是将文件中相关的代码封装成一个代码块,以方便于在程序的其他地方调用,减少代码的冗余.在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;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容