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

相关推荐
敲代码的嘎仔2 分钟前
力扣高频SQL基础50题详解
开发语言·数据库·笔记·sql·算法·leetcode·后端开发
码农-阿杰4 分钟前
Java 线程等待唤醒机制深度解析:synchronized、ReentrantLock、LockSupport 底层实现对比
java·开发语言·c++
赤水无泪5 分钟前
Qt 全模块汇总列表
开发语言·qt
yong999012 分钟前
MATLAB仿真计算电磁波回波信号的技术路径与实现指南
开发语言·matlab
不是光头 强19 分钟前
Spring Boot 多线程场景下 i18n 国际化失效问题排查与解决
java·开发语言·springboot
jieyucx19 分钟前
Go 语言核心关键字:defer 深度解析与实战避坑
开发语言·后端·golang·defer
星恒随风26 分钟前
四天学完前端基础三件套(JavaScript篇)
开发语言·前端·javascript·笔记
guslegend35 分钟前
第9节:前端工程与一键启动
前端·大模型·状态模式·ai编程
杜子不疼.1 小时前
【 C++ AI 大模型接入 SDK】 - 日志模块
开发语言·javascript·c++
南囝coding1 小时前
Anthropic 内部数百个 Claude Code Skills,他们总结的这套方法值得看
前端·后端