关于模块和require,module,exports,module.exports的关系

require函数的伪代码:

复制代码
const result = require('.myModule')
function require(modulePath) {
    // 1.modulePath转为绝对路径
    // 2.判断是否该模块已有缓存 如果有则返回缓存
    // 3.读取文件内容
    // 4.包裹到一个函数里面

  function __temp(module, exports,require, __dirname, __filename) {

    // 以下为modulePath文件内容
    console.log(__dirname, __filename);
    exports.c = 3;
  //错误写法  
    module.exports = {
      a: 1,
      b: 2,
    };
    this.m = 5;
  }

  module.exports = {};

  const exports = module.exports;

  __temp.call(
    module.exports,
    module,
    exports,
    require,
    module.path,
    module.filename
  );
}


 
复制代码

 

当一个js文件被require的时候 module会自动传入进去,而且__temp会绑定module.exports,所以在js模块里面this === module.exports === exports   但是这三个最好不要混用   比如上面的错误代码混写 module.exports 赋值了一个新对象 会导致 module.exports 和 exports不相等  但是最后导出的是module.exports  导致后面再去改this和exports对象的值都不会导出  因为只会导出最后给module.exports赋值的对象。
上面代码不给module.exports赋值对象 就不会有问题  

module.exports.a = 1
module.exports.b = 2
所以module导出的时候 不要混用这三个就不会有问题
 
 
 

posted on   龍瀧尨呀  阅读(9)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示