示例工程 01-orientation

01-orientation/03-file-protocol-esm/main.js

javascript · 1.4 KB

运行:01 · file:// 下 ESM 失败的最小复现

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

// main.js —— 解释 file:// 下 ES module 为什么加载失败
// 判据是「页面协议」,所以核心逻辑是一个纯函数,Node 里可直接断言。
 
export function diagnose(protocol) {
  if (protocol === 'file:') {
    return {
      ok: false,
      reason:
        'file:// 页面的源是 null(不透明源)。浏览器加载 module 脚本时会发跨源请求,' +
        '而 file:// 响应无法提供 Access-Control-Allow-Origin,请求被 CORS 拦下。',
      fix: '用静态服务器打开:node scripts/serve.mjs,然后访问 http://localhost:8080/...',
    };
  }
  if (protocol === 'http:' || protocol === 'https:') {
    return {
      ok: true,
      reason: 'HTTP(S) 页面的源是可序列化的正常源,同源的 module 请求可以直接加载。',
      fix: '无需修复。',
    };
  }
  return {
    ok: false,
    reason: `未知协议 "${protocol}",浏览器不会把它当作可加载模块的源。`,
    fix: '改用 http:// 或 https:// 打开。',
  };
}
 
export function run(log = console.log) {
  if (typeof location === 'undefined') {
    throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
  }
  const result = diagnose(location.protocol);
  log(`页面协议:${location.protocol}`);
  log(`ESM 能否加载:${result.ok ? '能' : '不能'}`);
  log(`原因:${result.reason}`);
  log(`处理:${result.fix}`);
  return result;
}