// main.js —— CommonJS 的循环依赖:拿到的是「半成品」 // 加载器先注册空 exports,再执行工厂;循环回到尚未执行完的模块时,只能看到已有属性。 export function createRuntime(factories) { const cache = new Map(); function require(id) { if (cache.has(id)) return cache.get(id).exports; const factory = factories[id]; if (!factory) throw new Error(`Cannot find module '${id}'`); const module = { exports: {} }; cache.set(id, module); factory(module, module.exports, require); return module.exports; } return { require, cache }; } export const FACTORIES = { './a': (module, exports, require) => { exports.name = 'a'; const b = require('./b'); exports.bName = b.name; exports.bSawA = b.sawA; }, './b': (module, exports, require) => { exports.name = 'b'; const a = require('./a'); // 此时 a 还没执行完 exports.sawA = a.name; exports.aBName = a.bName; // undefined:a.bName 尚未赋值 }, }; export function run(log = console.log) { const { require, cache } = createRuntime(FACTORIES); const a = require('./a'); const b = require('./b'); const rows = [ ['a 的最终值', JSON.stringify(a)], ['b 的最终值', JSON.stringify(b)], ['b 看到的 a.bName', String(b.aBName)], ['a 看到的 b.sawA', String(a.bSawA)], ['缓存中的模块数', String(cache.size)], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:循环依赖不会报错,但某一方会拿到未完成的 exports;字段是否存在取决于执行顺序。'); return rows; }