示例工程 14-module-resolution-import-maps

14-module-resolution-import-maps/01-import-map-basic/main.js

javascript · 1.5 KB

运行:14 · import map 基础

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— import map 的解析模型
// 浏览器只认 URL 与 import map 里的映射,不读 node_modules。
 
export function resolveSpecifier(map, specifier) {
  if (specifier.startsWith('./') || specifier.startsWith('../') || specifier.startsWith('/')) {
    return specifier;
  }
  const imports = (map && map.imports) || {};
  if (Object.hasOwn(imports, specifier)) return imports[specifier];
  if (Object.hasOwn(imports, specifier + '/')) {
    throw new Error(`前缀映射 ${specifier}/ 需要具体子路径`);
  }
  return null;
}
 
export function isBare(specifier) {
  return !(
    specifier.startsWith('./') ||
    specifier.startsWith('../') ||
    specifier.startsWith('/') ||
    /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(specifier)
  );
}
 
export function run(log = console.log) {
  const map = {
    imports: {
      'math-lib': './lib/math.js',
      'utils/': './lib/utils/',
    },
  };
 
  const rows = [
    ['math-lib 是否裸说明符', String(isBare('math-lib'))],
    ['math-lib 解析结果', resolveSpecifier(map, 'math-lib')],
    ['./lib/math.js 是否裸说明符', String(isBare('./lib/math.js'))],
    ['./lib/math.js 解析结果', resolveSpecifier(map, './lib/math.js')],
    ['未映射的 lodash', String(resolveSpecifier(map, 'lodash'))],
  ];
 
  log('场景 => 结果');
  for (const [label, value] of rows) log(`${label} => ${value}`);
  log('-'.repeat(50));
  log('要点:裸说明符必须由 import map 映射;相对/绝对路径原样交给 URL 解析。');
  return rows;
}