浏览器的 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"

相关推荐
Rabitebla1 天前
【数据结构】动态顺序表实现详解:从原理到接口设计(面试视角)
c语言·开发语言·数据结构·c++·面试·职场和发展
Beginner x_u1 天前
前端八股整理(Vue 02)|组件通信、生命周期、v-if 与 v-show
前端·javascript·vue.js
郝学胜-神的一滴1 天前
Linux 高并发基石:epoll 核心原理 + LT/ET 触发模式深度剖析
linux·运维·服务器·开发语言·c++·网络协议
A_aspectJ1 天前
Java开发的学习优势:稳定基石与多元可能并存的技术赛道
java·开发语言
qq_283720051 天前
Python 模块精讲:collections —— 高级数据结构深度解析(defaultdict、Counter、deque)
java·开发语言
一颗青果1 天前
Cookie 与 Session 超详细讲解
服务器·前端·github
zs宝来了1 天前
React 18 并发模式:Fiber 架构与时间切片
前端·javascript·框架
wjs20241 天前
Chart.js 饼图指南
开发语言
YSF2017_31 天前
C语言-12-静态库制作
c语言·开发语言
万物得其道者成1 天前
Vue3 使用 Notification 浏览器通知,解决页面关闭后旧通知点击无法跳转问题
前端·vue.js·edge浏览器