Node.js中exports,module.exports以及require方法
在Node.js中,使用module.exports.f = ...与使用exports.f = ...是一样的,此时exports就是module.exports的一种简写方式。但是,需要注意的是,如果直接给exports赋值的话,exports就与module.exports没有任何关联了,比如:
exports = { hello: false }; // Not exported, only available in the module
此时,exports是没有导出任何变量的。
要弄清楚之所以会发生这种事情,可以看一下require方法的实现方式:
function require(/* ... */) { const module = { exports: {} }; ((module, exports) => { // Module code here. In this example, define a function. function someFunc() {} exports = someFunc; // At this point, exports is no longer a shortcut to module.exports, and // this module will still export an empty default object. module.exports = someFunc; // At this point, the module will now export someFunc, instead of the // default object. })(module, module.exports); return module.exports; }
从代码中可以看到,在module文件里面的exports变量,实际上就是module.exports,如果在module文件里面给exports变量赋值了,那么exports变量就指向了其他对象,而require方法返回的是module.exports。上面的代码可以用下图表示:
参考链接:
https://nodejs.org/api/modules.html#modules_the_module_wrapper
分类:
javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2013-10-21 java中的IO流读取文件