// main.js —— import map 的 scopes:按「导入方 URL 前缀」覆盖映射 export function resolveWithScopes(map, specifier, importerUrl) { const scopes = (map && map.scopes) || {}; let bestScope = null; for (const scope of Object.keys(scopes)) { if (importerUrl.startsWith(scope) && (!bestScope || scope.length > bestScope.length)) { bestScope = scope; } } if (bestScope && Object.hasOwn(scopes[bestScope], specifier)) { return scopes[bestScope][specifier]; } const imports = (map && map.imports) || {}; return Object.hasOwn(imports, specifier) ? imports[specifier] : null; } export function run(log = console.log) { const map = { imports: { util: './global/util.js' }, scopes: { './vendor/': { util: './vendor/util.js' }, }, }; const rows = [ ['app.js 里的 util', resolveWithScopes(map, 'util', './app.js')], ['vendor/lib.js 里的 util', resolveWithScopes(map, 'util', './vendor/lib.js')], ['vendor/deep/x.js 里的 util', resolveWithScopes(map, 'util', './vendor/deep/x.js')], ['scopes 未命中的 lodash', String(resolveWithScopes(map, 'lodash', './vendor/lib.js'))], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:scopes 按最长前缀匹配;未命中时回退到顶层 imports。'); return rows; }