全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-23 5 分钟 ✍️ juanwangdev

模块脚本引入

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 处理模块依赖和编译

📝 发现内容有误?点击此处直接编辑

← 上一篇 index.html 入口文件
下一篇 → define 定义全局常量
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库