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

相关推荐
用户69371750013847 小时前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github
饮水桶_T7 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
炸膛坦客8 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
涛涛ing8 小时前
线上突发大面积白屏,排查一天后,我发现是 `JSON.parse` 背了锅
前端
小小小小宇8 小时前
Chrome 扩展如何操作浏览器:chrome.debugger 与 CDP 的区别
javascript
狮子座的男孩8 小时前
javascript 基础 es6:1、let 声明,let 实践案例,const 声明,解构赋值
前端·javascript·经验分享·es6·const声明·解构赋值·let声明及案例
reasonsummer8 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
咖啡八杯8 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
KevinWang_9 小时前
iOS 开发计划(二) - JavaScript 基本语法
javascript
KevinWang_9 小时前
iOS 开发计划(一) - 通过 Scriptable app 在 iOS 上运行 JavaScript 脚本
javascript·ios