浏览器的 JS 模块化支持观察记录

浏览器的 JS 模块化支持观察记录

1、具体实现
  • 文件结构

    module_test
    ├── test.html
    ├── test.js
    └── math.js

  1. index.html
html 复制代码
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>test</title>
    </head>

    <body></body>

    <script type="module" src="test.js"></script>

    <!-- <script type="module">
        import { add } from "./math.js";

        const result = add(2, 3);
        console.log(result);
    </script> -->
</html>
  1. test.js
js 复制代码
import { add } from "./math.js";

const result = add(2, 3);
console.log(result);
  1. math.js
js 复制代码
export function add(a, b) {
    return a + b;
}
2、测试
  • 直接在浏览器中打开 test.html 文件,输出如下错误信息

    Access to script at 'file:///D:/WebCode/module_test/test.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: chrome-extension, chrome-untrusted, data, edge, http, https, isolated-app.
    Failed to load resource: net::ERR_FAILED
    Unsafe attempt to load URL file:///D:/WebCode/module_test/test.html from frame with URL file:///D:/WebCode/module_test/test.html. 'file:' URLs are treated as unique security origins.

3、问题原因
  • 这是 ES Modules 在 file:// 协议下的 CORS 限制,这是浏览器的安全策略
  1. 浏览器将 file:// 协议视为不安全的 null origin

  2. ES Modules 要求通过 HTTP/HTTPS 协议加载,不能使用 file:// 协议

  3. file:// 页面加载另一个 file:// 文件被视为跨域请求

4、处理策略
  • 使用 VSCode 的 Live Server 插件,打开 test.html 文件
5、补充学习
js 复制代码
import { add } from "math.js";

const result = add(2, 3);
console.log(result);
  • test.js,写成上述内容,通过 Live Server 插件,打开 test.html 文件,输出如下错误信息

    Uncaught TypeError: Failed to resolve module specifier "math.js". Relative references must start with either "/", "./", or "../".

  1. 浏览器必须明确知道模块的完整路径,裸模块名(不以 /./../ 开头)不会被浏览器自动解析

  2. 使用相对路径导入模块,import { add } from "./math.js"

相关推荐
lichenyang4537 小时前
Docker 学习笔记(一):为什么需要镜像、容器和仓库?
前端
kyriewen7 小时前
别再对着 TypeScript 报错发呆了:我把 10 个最常见的红色波浪线翻译成了人话
前端·javascript·typescript
IT_陈寒7 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
free358 小时前
从 0 实现一个 Tiny JavaScript VM:项目架构拆解
javascript
奇奇怪怪的8 小时前
Embedding 模型 10+ 横向评测
前端
陈广亮8 小时前
Monorepo 从 0 到 1 实操指南 2026 版:pnpm catalogs + Turborepo 2.x + changesets 全链路
前端
子兮曰8 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程
敲代码的鱼8 小时前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·前端·ios
子兮曰8 小时前
前端工具链的「Rust 化」:一场没有赢家的军备竞赛?
前端·后端·rust