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

posted @   chaoguo1234  阅读(509)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2013-10-21 java中的IO流读取文件
点击右上角即可分享
微信分享提示