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 @ 2024-05-08 16:25  冰凉小手  阅读(18)  评论(0)    收藏  举报