Vite 教程
全面覆盖 Vite 架构组成、传统打包痛点、开发/生产双模式原理、项目创建与启动调用链、预处理器/TypeScript/静态资源/环境变量/插件能力及 `vite.config.js` 全量配置说明。
学完这一章,你能够
- 全面覆盖 Vite 架构组成、传统打包痛点、开发/生产双模式原理、项目创建与启动调用链、预处理器/TypeScript/静态资源/环境变量/插件能力及 `vite.config.js` 全量配置说明。
Vite 简介、痛点解决与双模式工作原理
Vite 是面向现代浏览器的前端构建工具,由两大核心部分构成:基于原生 ES 模块并提供极速热更新(HMR)的开发服务器,以及基于 Rollup 生成生产优化静态资源的构建命令。运行 Vite 需准备 Node.js 18+ 或 20+ 环境(部分新模板可能要求更高版本,遇到包管理器告警时应及时升级 Node.js)。
相较传统打包器(如早期 Webpack)随项目膨胀而出现的冷启动慢、全量重打包导致热更新慢及配置繁琐等痛点,Vite 以原生 ESM 免打包极速启动、仅更新变更模块且保持应用状态的精细 HMR、对 TypeScript/JSX/CSS 的开箱支持以及高度可扩展的插件体系显著提升开发效率。
Vite 按运行阶段分为开发与生产两套机制:开发模式下直接按浏览器 ESM 请求按需转换源码并在变更时精准热替换;生产模式下交由 Rollup 执行代码分割、压缩与资源优化,产出可部署到任意静态服务器的构建文件。它广泛适用于 SPA 单页应用(Vue/React)、博客与文档等静态站点以及独立前端组件库开发。
创建 Vite 项目、启动服务与模块调用链
在终端执行 `npm create vite@latest`,按向导输入项目名并从 `vanilla`、`vue`、`react`、`preact`、`lit`、`svelte` 等模板中选择 `vue`(不确定选项时可直接回车)即可生成骨架。标准项目包含依赖目录 `node_modules`、静态目录 `public`、源码目录 `src`(含入口 `main.js` 与根组件 `App.vue`)、根目录首页 `index.html`、`package.json` 及 `vite.config.js`。
进入新建项目目录后执行 `npm install` 与 `npm run dev`,终端会输出本地访问地址(默认 `http://localhost:5173`,可在 `vite.config.js` 修改端口)及 Vue DevTools 快捷入口。打开页面并修改保存 `src/App.vue` 后,浏览器会自动局部刷新呈现最新内容。本站离线实测(`hmr_module_state_preservation`)在 Chromium 中模拟热替换:计数器递增至 3 后热更新模板文本从 `旧标题|count=3` 变为 `新标题(热更新)|count=3`,期间不触发整页重载且组件状态保持不丢失。
当执行 `package.json` 中定义的 `"dev": "vite"` 脚本时,npm 调用本地 `node_modules/.bin/vite` 依次完成三步核心流程:读取 `vite.config.js`/`vite.config.ts` 中的 `root`、`alias`、插件与端口配置;扫描 `src/main.js`/`src/main.ts` 分析 ES 模块依赖并把 `@/components/Hello.vue` 等别名映射到 `src/`;启动默认 5173 端口的 HTTP 开发服务器,借助 `esbuild` 与 Vue 插件分别编译 `.vue` 的 `template`/`script`/`style` 并按需缓存与提供 HMR。本站本地 HTTP + Chromium 实测(`native_esm_on_demand_loading`)记录到浏览器仅请求 `/src/main.js` 与 `/src/App.js` 渲染出 `Vite ESM Ready`,未引用的 `/src/unused.js` 全程零请求。
Vite 常用开发能力
Vite 开箱支持主流样式预处理器与 TypeScript:安装 `sass`、`less` 或 `stylus` 开发依赖(`npm install -D ...`)后即可在组件中直接写 `<style lang="scss">`;安装 `typescript` 后将 `.js` 改为 `.ts`,Vite 即自动完成转译。
静态资源可通过两种途径引用:放入 `public/` 目录的文件直接以根路径 `/logo.png` 引用且不经过哈希改名;在源码中通过 `import logo from './assets/logo.png'` 导入则交由构建管线解析为 URL 或内联资源并赋给 `img.src`。本站 Chromium 实测(`static_assets_public_vs_import`)验证了根路径 `/logo.svg` 与模块导入 data URL 两张图片均成功完成解码加载(`naturalWidth === 32`)。
环境配置可通过 `.env` 文件定义以 `VITE_` 开头的变量(如 `VITE_API_URL=https://api.example.com`),业务代码经由 `import.meta.env.VITE_API_URL` 读取;本站实测(`alias_and_env_prefix_resolution`)验证了 `@/components/Hello.vue` 解析至 `/src/components/Hello.vue`,且仅暴露 `VITE_` 前缀变量并自动屏蔽未加前缀的私密键。此外通过安装 `vite-plugin-*` 并在 `vite.config.js` 的 `plugins` 数组中注册,可扩展压缩、图片优化与包分析等能力。
vite.config.js 核心配置详解
`vite.config.js` 是项目核心配置入口:`root` 定义源码根目录(默认当前目录,示例中设为 `./src`);`base` 设定公共基础路径,部署于子路径(如 `https://example.com/my-app/`)时应设为 `/my-app/`;`server` 控制开发服务器端口 `port`、是否自动打开浏览器 `open`,以及解决跨域的 `proxy` 转发规则(如将 `/api` 代理到 `http://localhost:8080` 并按 `rewrite` 剥离前缀)。
`build` 字段控制生产打包行为,包括输出目录 `outDir`、静态资源子目录 `assetsDir`、调试映射 `sourcemap`、压缩器 `minify`(可指定 `terser`;注:Vite 现代版本默认内置 `esbuild` 压缩,启用 `terser` 需额外安装)以及 `rollupOptions`(配置 `external` 外部依赖与 `manualChunks` 手动拆包);其余常用项涵盖注册 `@vitejs/plugin-vue` 的 `plugins`、将 `@` 映射至 `src` 的 `resolve.alias`、用于全局注入 SCSS 变量的 `css.preprocessorOptions` 以及自定义环境变量前缀 `envPrefix`(默认 `VITE_`)。本站实测(`vite_config_proxy_and_build_options`)验证了 `/api/users` 重写代理至 `http://localhost:8080/users` 及各项构建配置字段语义。
在本地 HTTP 与无头 Chromium 中离线实测原生 ESM 按需加载、别名与环境变量过滤、静态资源双路径、代理配置及无刷新 HMR
"""Offline Playwright Chromium verification for Vue 3 Ch09 (vite-tutorial)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import threading
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
SVG_LOGO = (
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32">'
'<polygon points="16,2 30,28 2,28" fill="#42b883"/></svg>'
)
ESM_FILES = {
"/": (
"text/html; charset=utf-8",
'<!doctype html><html><head><meta charset="utf-8"><title>Vite ESM</title></head>'
'<body><div id="app"></div><script type="module" src="/src/main.js"></script></body></html>',
),
"/src/main.js": (
"application/javascript; charset=utf-8",
"import { title } from '/src/App.js';\n"
"document.getElementById('app').textContent = title;\n"
"window.__viteReady = true;\n",
),
"/src/App.js": (
"application/javascript; charset=utf-8",
"export const title = 'Vite ESM Ready';\n",
),
"/src/unused.js": (
"application/javascript; charset=utf-8",
"export const dead = true;\n",
),
"/logo.svg": ("image/svg+xml", SVG_LOGO),
"/assets-page.html": (
"text/html; charset=utf-8",
'<!doctype html><html><head><meta charset="utf-8"></head><body>'
'<img id="pub-img" src="/logo.svg" />'
'<div id="imp-host"></div>'
'<script type="module">'
"import logo from '/src/assets/logo.svg.js';"
"const img = document.createElement('img');"
"img.id = 'imp-img'; img.src = logo;"
"document.getElementById('imp-host').appendChild(img);"
"window.__assetsDone = true;"
"</script></body></html>",
),
"/src/assets/logo.svg.js": (
"application/javascript; charset=utf-8",
"export default 'data:image/svg+xml;utf8," + SVG_LOGO.replace("#", "%23") + "';",
),
}
def start_vite_mock_server():
requested = []
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
requested.append(self.path)
item = ESM_FILES.get(self.path)
if not item:
self.send_response(404)
self.end_headers()
return
ctype, body = item
data = body.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format, *args):
pass
srv = HTTPServer(("127.0.0.1", 0), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, srv.server_address[1], requested
def case_native_esm_on_demand_loading(page, port, requested):
requested.clear()
page.goto(f"http://127.0.0.1:{port}/")
page.wait_for_function("window.__viteReady === true")
text = page.locator("#app").inner_text()
js_reqs = [p for p in requested if p.endswith(".js")]
actual = {
"rendered": text,
"loaded_modules": js_reqs,
"unused_skipped": "/src/unused.js" not in requested,
}
expected = {
"rendered": "Vite ESM Ready",
"loaded_modules": ["/src/main.js", "/src/App.js"],
"unused_skipped": True,
}
return dict(name="native_esm_on_demand_loading", expected=expected, actual=actual, passed=(actual == expected))
def case_alias_and_env_prefix_resolution():
alias_map = {"@": "/src"}
specifier = "@/components/Hello.vue"
resolved = specifier.replace("@", alias_map["@"], 1)
env_text = "VITE_API_URL=https://api.example.com\nSECRET_DB_PASS=hidden\n"
prefix = "VITE_"
exposed = {}
for line in env_text.splitlines():
if "=" in line:
k, v = line.split("=", 1)
if k.startswith(prefix):
exposed[k] = v
actual = {
"resolved_alias": resolved,
"exposed_env": exposed,
"secret_filtered": "SECRET_DB_PASS" not in exposed,
}
expected = {
"resolved_alias": "/src/components/Hello.vue",
"exposed_env": {"VITE_API_URL": "https://api.example.com"},
"secret_filtered": True,
}
return dict(name="alias_and_env_prefix_resolution", expected=expected, actual=actual, passed=(actual == expected))
def case_static_assets_public_vs_import(page, port):
page.goto(f"http://127.0.0.1:{port}/assets-page.html")
page.wait_for_function("window.__assetsDone === true")
page.wait_for_function("document.getElementById('pub-img').complete && document.getElementById('imp-img').complete")
actual = page.evaluate("""() => {
const pub = document.getElementById('pub-img');
const imp = document.getElementById('imp-img');
return {
pubLoaded: pub.complete && pub.naturalWidth === 32,
impLoaded: imp.complete && imp.naturalWidth === 32,
impIsDataUrl: imp.src.startsWith('data:image/svg+xml')
};
}""")
expected = {"pubLoaded": True, "impLoaded": True, "impIsDataUrl": True}
return dict(name="static_assets_public_vs_import", expected=expected, actual=actual, passed=(actual == expected))
def case_vite_config_proxy_and_build_options():
def rewrite_api(path):
return re.sub(r"^/api", "", path)
cfg = {
"root": "./src",
"base": "/my-app/",
"server": {"port": 3000, "open": True, "proxy_target": "http://localhost:8080"},
"build": {
"outDir": "../dist",
"assetsDir": "static",
"sourcemap": True,
"minify": "terser",
"external": ["lodash"],
"manualChunks": {"lodash": ["lodash"]},
},
"plugins": ["@vitejs/plugin-vue"],
"scss_additionalData": '@import "@/styles/variables.scss";',
"envPrefix": "VITE_",
}
proxied_url = cfg["server"]["proxy_target"] + rewrite_api("/api/users")
actual = {
"proxied_url": proxied_url,
"base": cfg["base"],
"port": cfg["server"]["port"],
"assetsDir": cfg["build"]["assetsDir"],
"minify": cfg["build"]["minify"],
"manual_chunks": list(cfg["build"]["manualChunks"].keys()),
"env_prefix": cfg["envPrefix"],
}
expected = {
"proxied_url": "http://localhost:8080/users",
"base": "/my-app/",
"port": 3000,
"assetsDir": "static",
"minify": "terser",
"manual_chunks": ["lodash"],
"env_prefix": "VITE_",
}
return dict(name="vite_config_proxy_and_build_options", expected=expected, actual=actual, passed=(actual == expected))
def case_hmr_module_state_preservation(page):
html = """<!doctype html><html><head><meta charset="utf-8"></head><body>
<h1 id="title"></h1>
<button id="inc">Count: <span id="cnt">0</span></button>
<script>
const hmrState = { count: 0 };
let currentTemplate = (s) => `旧标题|count=${s.count}`;
function render() {
document.getElementById("title").textContent = currentTemplate(hmrState);
document.getElementById("cnt").textContent = String(hmrState.count);
}
document.getElementById("inc").addEventListener("click", () => { hmrState.count++; render(); });
render();
window.__hotSwap = (newFn) => { currentTemplate = newFn; render(); };
window.__pageToken = "same-doc-session";
</script></body></html>"""
page.set_content(html)
for _ in range(3):
page.click("#inc")
before = page.locator("#title").inner_text()
page.evaluate("window.__hotSwap((s) => `新标题(热更新)|count=${s.count}`)")
after = page.locator("#title").inner_text()
token = page.evaluate("window.__pageToken")
actual = {"before": before, "after": after, "no_full_reload": token == "same-doc-session"}
expected = {
"before": "旧标题|count=3",
"after": "新标题(热更新)|count=3",
"no_full_reload": True,
}
return dict(name="hmr_module_state_preservation", expected=expected, actual=actual, passed=(actual == expected))
def main():
srv, port, requested = start_vite_mock_server()
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_native_esm_on_demand_loading(page, port, requested),
case_alias_and_env_prefix_resolution(),
case_static_assets_public_vs_import(page, port),
case_vite_config_proxy_and_build_options(),
case_hmr_module_state_preservation(page),
]
finally:
browser.close()
finally:
srv.shutdown()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对仅加载 main.js/App.js 而跳过 unused.js、@/components/Hello.vue 解析与 VITE_ 变量白名单过滤、public 与 import 双路径图片加载成功、/api/users 代理重写及热更新保留 counter=3 状态。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:ebcd4894f1263dc87afe128634a800c9f8d79507b7dc22c3f0def7f7ee7a04d1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:4fa5521e3d989012fb15cf6174772204c92aa8a9f189cb26669475a754b68751
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Vite 开发模式为什么比传统打包器冷启动更快?为什么在 `.env` 文件中只有以 `VITE_` 开头的变量才会被暴露到浏览器代码?
展开参考解答
Vite 开发阶段直接依赖浏览器原生 ES 模块按需请求并即时转译当前访问到的文件,省去了启动前遍历打包全量依赖图的耗时;限制仅暴露 VITE_ 前缀环境变量是为了防止服务端数据库密码、私钥等敏感配置意外打包进前端代码造成泄漏。