模块脚本引入
Vite 利用浏览器原生 ESM 支持,在 index.html 中使用 type="module" 引入模块脚本。
标准引入方式
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<!-- 使用 type="module" -->
<script type="module" src="/src/main.js"></script>
</body>
</html>
type="module" 特点
| 特点 | 说明 | |
|---|---|---|
| ES 模块 | 支持 import/export 语法 | |
| 异步加载 | 模块脚本异步执行 | |
| 严格模式 | 自动启用严格模式 | |
| 作用域 | 模块内变量不污染全局 |
内联模块脚本
HTML
<script type="module">
import { createApp } from 'vue'
import App from '/src/App.vue'
createApp(App).mount('#app')
</script>
引入路径规则
HTML
<!-- 绝对路径(从项目根目录) -->
<script type="module" src="/src/main.js"></script>
<!-- 相对路径(相对于 index.html) -->
<script type="module" src="./src/main.js"></script>
<!-- CDN 模块 -->
<script type="module" src="https://cdn.jsdelivr.net/npm/vue@3"></script>
注意:开发环境推荐使用绝对路径
/src/xxx。
模块解析过程
HTML
1. 浏览器请求 index.html
2. 解析 <script type="module" src="/src/main.js">
3. Vite 服务器接收请求,编译 /src/main.js
4. 返回编译后的 ES 模块
5. 浏览器执行 import 语句,递归加载依赖
多模块引入
text
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
<script type="module" src="/src/utils.js"></script>
</body>
要点总结
- type="module" 是引入 ES 模块的必要属性
- 支持绝对路径和相对路径
- 模块异步加载,自动严格模式
- Vite 处理模块依赖和编译
📝 发现内容有误?点击此处直接编辑