// main.js —— paths 与 shim 的解析模型 // 这两项配置是 AMD 适配「非 AMD 库」的关键,也是最容易配错的地方。 export function resolveId(paths, name) { return Object.hasOwn(paths, name) ? paths[name] : name; } export function joinUrl(baseUrl, id) { const raw = `${baseUrl.replace(/\/$/, '')}/${id}`; const withExt = /\.js$/.test(raw) ? raw : `${raw}.js`; const parts = []; for (const part of withExt.split('/')) { if (part === '' || part === '.') continue; if (part === '..') parts.pop(); else parts.push(part); } return `/${parts.join('/')}`; } export function pickShimExport(globalObject, shim, name) { const entry = shim[name]; if (!entry) return undefined; if (typeof entry.exports === 'string') { return entry.exports .split('.') .reduce((obj, key) => (obj == null ? undefined : obj[key]), globalObject); } return undefined; } export function run(log = console.log) { const paths = { legacy: '../legacy' }; const shim = { legacy: { exports: 'LegacyCounter' } }; const resolved = resolveId(paths, 'legacy'); const url = joinUrl('./amd', resolved); const fakeGlobal = { LegacyCounter: function LegacyCounter() { this.n = 0; }, }; fakeGlobal.LegacyCounter.prototype.inc = function () { this.n += 1; return this.n; }; const Ctor = pickShimExport(fakeGlobal, shim, 'legacy'); const counter = new Ctor(); counter.inc(); counter.inc(); const rows = [ ['paths 解析 legacy', resolved], ['相对 baseUrl 的 URL', url], ['shim.exports 取到的值', typeof Ctor === 'function' ? 'function LegacyCounter' : String(Ctor)], ['实例调用 inc() 两次', String(counter.n)], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:paths 把逻辑模块名映射到路径;shim.exports 把全局变量包装成模块返回值。'); return rows; }