CJS

declare function getModuleId(modulePath: string): string
declare function getDirname(dir: string): string
 
const moduleCache: Record<string, { [key: string]: any }> = {}
 
function require(modulePath: string) {
  // 获取模块 id,就是模块的完整绝对路径
  const moduleId = getModuleId(modulePath)
  // 判断缓存
  if (moduleCache[moduleId]) {
    return moduleCache[moduleId]
  }
 
  // 真正运行模块中的代码
  function _require(exports, require, module, __filename, __dirname) {
    // ----- 目标模块的代码在这里 -----
  }
 
  const module = {
    exports: {},
  }
  const exports = module.exports
  const __filename = moduleId
  const __dirname = getDirname(moduleId)
  // 运行模块的代码
  _require.call(exports, exports, require, module, __filename, __dirname)
  // 缓存 module.exports
  moduleCache[moduleId] = module.exports
  return module.exports
}