示例工程 01-orientation

01-orientation/03-file-protocol-esm/index.html

html · 1.2 KB

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

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

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>01 · file:// 下 ESM 失败的最小复现</title>
  <style>
    .banner { padding: 12px; border: 1px solid #999; font-family: monospace; }
    .bad { background: #fee; }
    .good { background: #efe; }
  </style>
</head>
<body>
  <div id="banner" class="banner">检测中…</div>
 
  <script>
    // 这段是 classic 脚本,file:// 下照样能跑,所以它能报出「为什么下面的 module 挂了」
    var banner = document.getElementById('banner');
    if (location.protocol === 'file:') {
      banner.className = 'banner bad';
      banner.textContent =
        '你正在用 file:// 打开。下面的 module 会在 Console 里报 CORS 错误。' +
        '请改用 node scripts/serve.mjs 并以 http:// 访问。';
    } else {
      banner.className = 'banner good';
      banner.textContent = '协议是 ' + location.protocol + ',module 可以正常加载。';
    }
  </script>
 
  <!-- 这一行就是复现点:file:// 下它会被 CORS 拦掉,run() 永远不会执行 -->
  <script type="module">
    import { run } from './main.js';
    run();
  </script>
</body>
</html>