commonjs模块化

require函数的大致执行细节

  1. 把传入的fileName转化为绝对路径(fileName可以是绝对路径,相对路径,后缀名可以省略,可以是路径)
  2. 判断是否该模块已有缓存,有缓存则返回缓存;没有则进入下一步
  3. 读取文件内容
  4. 创建运行函数,函数体即为文件内容(模块会在函数环境运行)
  5. 创建模块结构module对象
  6. 运行函数,绑定this为module.exports并传入module对象与其他参数
  7. 缓存模块
  8. 返回module.exports
require("./module")
function require(fileName){
// 1. 把传入的path转化为绝对路径
...
const fileName =' D:\\test\\src\\myModule.js'
// 2. 判断是否该模块已有缓存,有缓存则返回缓存;没有则进入下一步
if(require.cache[path]) return require.cache[path]
// 3. 读取文件内容
const context = ...
// 4. 创建运行函数,函数体即为文件内容
function __temp(module, exports, require, __dirname, __filename){
context
}
// 5. 创建模块结构module对象
const PATH = require('path')
const module = {
exports: {},
path: PATH.dirname(fileName),
fileName,
...
}
const exports = module.exports
// 6. 运行函数,绑定this为module.exports并传入module对象与其他参数
__temp.call(module.exports, module, exports, require, module.path, module.fileName)
// 7. 缓存模块
require.cache[path]= module
// 8. 返回module.exports
return module.exports
}
posted @   冰凉小手  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示