Vue.js: Vite 工程化配置
最后更新:2026-08-26
Vite 是 Vue 3 团队推出的下一代构建工具,冷启动比 Webpack 快 30x。Vite 5/6 在 TypeScript、SSR、构建优化等方面有巨大改进,是现代 Vue 项目的标配。
本课带你掌握 Vite 5/6 的完整工程化配置:vite.config.ts、alias 别名、env 变量、SCSS、自动导入、构建优化。这是企业级 Vue 项目的必备技能。
1. 你将学到
- vite.config.ts 完整配置(alias / server / build / css / plugins)
- 3 种环境变量(VITE_ 前缀)
- SCSS / Less 预处理器集成
- unplugin-auto-import 自动导入 ref / computed
- path.resolve 路径别名
- 5 大构建优化(chunk 分割、tree-shaking、压缩、CDN、Source Map)
- Vite 5/6 vs Vite 4 关键差异
2. 一个 5 分钟冷启动的"工程师体验"对比
(1) 痛点:Webpack 冷启动 30 秒,开发者等崩溃
Alice 的团队用的是 Webpack:
BASH
# Webpack 项目冷启动
$ npm run dev
> Project is running at http://localhost:8080
> Compiled successfully in 28.5s ← 等了 30 秒
团队负责人 Charlie:
"Alice,开发服务器启动要 30 秒。每次保存文件,热更新要 3 秒。我们得换 Vite。"
(2) Vite 解法:5 秒冷启动,毫秒级 HMR
BASH
# Vite 项目冷启动
$ npm run dev
> VITE v5.4.0 ready in 487 ms ← 仅 0.5 秒
> Local: http://localhost:5173/
开发体验对比:
| 操作 | Webpack 5 | Vite 5 |
|---|---|---|
| 冷启动 | 28s | 0.5s |
| HMR | 1-3s | < 50ms |
| 大项目构建 | 30-60s | 5-15s |
56x 冷启动速度提升。换 Vite 后开发效率显著提升。
(3) 收益
切换到 Vite 后:
- 冷启动:28s → 0.5s(-98%)
- HMR:3s → 50ms(-98%)
- 构建:30s → 10s(-67%)
- 开发者满意度:显著提升
3. Vite 5/6 核心概念
(1) Vite 双模式
TEXT
📖 仅展示
开发模式(dev):
- 用原生 ESM,浏览器直接 import
- 按需编译(首次访问页面才编译)
- HMR 极快(只更新改动的模块)
生产模式(build):
- 用 Rollup 打包
- 自动 tree-shaking / 代码分割 / 压缩
- 输出到 dist/ 目录
(2) 5 大核心优势
| 优势 | 说明 |
|---|---|
| 极速冷启动 | esbuild 预构建依赖(Go 写的,比 JS 写的 babel 快 100x) |
| 按需编译 | 只编译当前访问的模块,不编译整个项目 |
| 原生 ESM | 浏览器直接 <script type="module"> 加载 |
| HMR 极快 | 改 1 个文件,只更新这 1 个模块 |
| SSR / SSG | 一等支持(Nuxt 3 官方推荐) |
(3) Vite 5/6 vs Vite 4
| 维度 | Vite 4 | Vite 5/6 |
|---|---|---|
| 启动速度 | 快 | 更快(优化依赖预构建) |
| 构建速度 | 5-15s | 3-8s |
| Node 要求 | 14+ | 18+ |
| Rollup | 3.x | 4.x |
| 默认 ESM | ✅ | ✅ |
| 推荐度 | 旧 | ⭐⭐⭐⭐⭐ |
4. vite.config.ts 完整配置
(1) 基本结构
TS
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
// 项目根目录(默认 process.cwd())
root: '.',
// 基础公共路径
base: '/',
// 插件
plugins: [vue()],
// 服务器配置
server: {
port: 5173,
open: true, // 自动打开浏览器
host: '0.0.0.0' // 局域网可访问
},
// 构建配置
build: {
outDir: 'dist',
sourcemap: false,
minify: 'esbuild'
},
// CSS 配置
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
},
// 路径别名
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
}
})
(2) 5 大核心配置
TS
export default defineConfig({
// 1. 路径别名(最常用)
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'@components': path.resolve(__dirname, 'src/components'),
'@stores': path.resolve(__dirname, 'src/stores')
}
},
// 2. 服务器配置
server: {
port: 5173,
open: true,
host: '0.0.0.0',
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
},
// 3. CSS 预处理器
css: {
preprocessorOptions: {
scss: { /* ... */ },
less: { /* ... */ }
}
},
// 4. 构建优化
build: {
rollupOptions: {
output: {
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia']
}
}
},
chunkSizeWarningLimit: 1500
},
// 5. 优化选项
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia']
}
})
5. 3 种环境变量
(1) VITE_ 前缀规则
BASH
# .env.development
VITE_API_BASE_URL=http://localhost:3000
VITE_APP_TITLE=My App (Dev)
# .env.production
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=My App
# .env.local(git 忽略,每个开发者自己的)
VITE_API_KEY=secret-key
(2) TypeScript 类型定义
TS
// src/env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_APP_TITLE: string
readonly VITE_API_KEY?: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
(3) 组件中使用
TS
const apiUrl = import.meta.env.VITE_API_BASE_URL
const title = import.meta.env.VITE_APP_TITLE
(4) 4 个 .env 文件优先级
| 文件 | 用途 | Git |
|---|---|---|
.env |
所有环境共享 | 提交 |
.env.development |
仅开发 | 提交 |
.env.production |
仅生产 | 提交 |
.env.local |
本地覆盖(不提交) | 忽略 |
6. SCSS 集成
(1) 安装
BASH
npm install -D sass
(2) 全局变量
SCSS
// src/styles/variables.scss
$primary: #42b883;
$danger: #ef4444;
$font-size-base: 14px;
$border-radius: 4px;
TS
// vite.config.ts
css: {
preprocessorOptions: {
scss: {
// 自动导入到每个 .scss 文件
additionalData: `@import "@/styles/variables.scss";`
}
}
}
SCSS
// 任何 .scss 文件中都能直接用
.button {
background: $primary; /* 无需 @import */
color: white;
border-radius: $border-radius;
}
(3) 5 大 SCSS 优势
- 变量:$primary, $danger
- 嵌套:父子选择器
- mixin:复用样式块
- 函数:lighten($primary, 10%)
- 模块化:@use / @forward
7. unplugin-auto-import 自动导入
(1) 安装
BASH
npm install -D unplugin-auto-import
(2) 配置
TS
// vite.config.ts
import AutoImport from 'unplugin-auto-import'
export default defineConfig({
plugins: [
vue(),
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts', // 类型定义
eslintrc: {
enabled: true // 生成 .eslintrc-auto-import.json
}
})
]
})
(3) 使用
VUE
<script setup>
// ✅ 不再需要 import ref / computed / watch
const count = ref(0)
const double = computed(() => count.value * 2)
watch(count, (val) => console.log(val))
// ✅ 不再需要 useRouter
const router = useRouter()
</script>
(4) 5 大优势
| 优势 | 说明 |
|---|---|
| 减少 import | 不用每次写 import ref / computed |
| 类型安全 | dts 文件自动生成类型 |
| 可配置 | 可指定要自动导入的 API |
| ESLint 兼容 | 自动生成 .eslintrc 避免 import 警告 |
| 构建快 | 不影响打包速度 |
8. 5 大构建优化
(1) 代码分割(manualChunks)
TS
// vite.config.ts
build: {
rollupOptions: {
output: {
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia'],
'echarts-vendor': ['echarts', 'vue-echarts'],
'utils': ['axios', 'dayjs']
}
}
}
}
(2) Tree-shaking(默认开启)
TS
build: {
rollupOptions: {
treeshake: {
moduleSideEffects: 'no-external', // 标记所有模块无副作用
propertyReadSideEffects: false // 标记属性读取无副作用
}
}
}
(3) CSS 压缩
TS
build: {
cssMinify: 'lightningcss', // 比 esbuild 快 10x
// 或 'esbuild'(默认)
}
(4) 资源处理
TS
build: {
assetsInlineLimit: 4096, // < 4KB 资源 inline(base64)
rollupOptions: {
output: {
assetFileNames: 'assets/[name]-[hash][extname]',
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js'
}
}
}
(5) Source Map(生产环境调试)
TS
build: {
sourcemap: true, // 生产环境也生成(用于 Sentry)
rollupOptions: {
output: {
sourcemapExcludeSources: true // 不把源码 inline 到 map
}
}
}
9. 完整示例:5 大 Vite 配置场景
▶ 示例:完整 vite.config.ts(⚠️ 需 Vite 项目)
⚠️ 以下代码在
vite.config.ts 中使用,CDN 全局构建不适用。展示核心配置项:
TS
📖 仅展示
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import'
import path from 'path'
export default defineConfig({
plugins: [
vue(),
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts'
})
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src') // @ → src/
}
},
server: {
port: 5173, open: true, // 启动后自动打开
proxy: {
'/api': {
target: 'http://localhost:3000', // 代理转发
changeOrigin: true
}
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/styles/variables.scss";'
}
}
},
build: {
outDir: 'dist', sourcemap: true,
rollupOptions: {
output: {
manualChunks: { 'vue-vendor': ['vue', 'vue-router', 'pinia'] }
}
}
}
})
▶ 示例:3 种环境变量配置
BASH
# .env.development (开发)
VITE_API_BASE_URL=http://localhost:3000
# .env.production (生产)
VITE_API_BASE_URL=https://api.example.com
# .env.local (本地,不入 Git)
VITE_API_KEY=secret
TS
// src/env.d.ts(TypeScript 声明)
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_API_KEY?: string
}
TS
// 在 .vue / .ts 中使用
const apiUrl = import.meta.env.VITE_API_BASE_URL
▶ 示例:5 大构建优化
| 优化 | 配置 |
|---|---|
| 代码分割 | rollupOptions.output.manualChunks |
| Tree-shaking | build.treeshake 配置 |
| CSS 压缩 | build.cssMinify: 'lightningcss' |
| 资源处理 | build.assetsInlineLimit + 文件名 |
| Source Map | build.sourcemap: true |
▶ 示例:5 个常见错误速查
| 错误 | 现象 | 解决 |
|---|---|---|
| 路径别名不生效 | import 失败 | path.resolve 用 __dirname |
| SCSS 变量未定义 | 编译报错 | additionalData 自动导入 |
| 环境变量 undefined | 运行时 undefined | 用 VITE_ 前缀 + .env 文件 |
| auto-import 不工作 | ref 找不到 | 检查 dts 文件生成 |
| 生产环境白屏 | 路径错误 | 配置 base: '/yourpath/' |
▶ 示例:5 大 Vite 性能对比
| 配置 | 冷启动 | HMR | 生产构建 |
|---|---|---|---|
| 默认 | 0.5s | 50ms | 10s |
| + alias | 0.5s | 50ms | 10s |
| + SCSS | 0.6s | 60ms | 11s |
| + auto-import | 0.6s | 60ms | 11s |
| + manualChunks | 0.6s | 60ms | 12s(但首屏快 50%) |
❓ 常见问题
Q Vite 5/6 最低 Node 版本?
A Node 18+(2023-10 起)。Node 16 已 EOL。Vite 4 还支持 Node 14+。
Q 路径别名 path.resolve 的 __dirname 在 ESM 怎么用?
A 用
import.meta.url:fileURLToPath(new URL('./src', import.meta.url))。Vite 5 推荐用 resolve.alias + path.resolve 配合。Q 环境变量 VITE_ 前缀必须吗?
A 是的。Vite 默认只暴露 VITE_ 前缀的变量(安全考虑)。其他变量不会被打包。
Q auto-import 在生产环境能用吗?
A 能。
unplugin-auto-import 在 build 时会移除 auto-import 代码(变成显式 import),不影响打包。Q Vite 和 Webpack 选哪个?
A 新项目一律 Vite。Webpack 仅维护老项目。Vite 冷启动 30x 快,HMR 60x 快。
Q Vite SSR 怎么配置?
A 用
vite build --ssr 或 Nuxt 3 集成。SSR 配置略复杂(需要处理 hydration),但 Vite 官方支持好。Q unplugin-auto-import 的 dts 文件什么时候生成?
A dev 服务器启动时 + build 时。手动可手动跑
npx auto-imports 生成。📖 小节
- Vite 5/6 冷启动 0.5s,HMR 50ms(vs Webpack 28s/3s)
- vite.config.ts 5 大核心:plugins / server / build / css / resolve.alias
- 3 种环境变量:VITE_ 前缀 + 4 个 .env 文件
- SCSS 自动导入:
additionalData+ variables.scss - unplugin-auto-import:ref / computed / useRouter 不再 import
- 5 大构建优化:代码分割 / tree-shaking / CSS 压缩 / 资源处理 / Source Map
- Vite 是 Vue 3 官方推荐构建工具
📝 作业
-
基础题(难度⭐) 创建一个 Vite + Vue 3 项目,配置:
- 路径别名 @ → src
- SCSS 全局变量
- 一个 .env.development 含 VITE_API_BASE_URL
-
进阶题(难度⭐⭐) 完整 Vite 配置:
- 路径别名(@ / @components / @stores)
- SCSS + 自动导入 variables
- unplugin-auto-import(vue + vue-router + pinia)
- 代理 /api 到后端
- 生产构建 manualChunks(vue-vendor)
-
挑战题(难度⭐⭐⭐) 实现完整的"企业级 Vite 配置":
- 5 大路径别名(@ / @components / @stores / @utils / @composables)
- SCSS 全局变量 + 5 个 mixin(flex / card / button / form / responsive)
- unplugin-auto-import + Volar 类型生成
- 3 种环境变量(dev / staging / prod)
- 5 大构建优化(manualChunks / tree-shaking / lightningcss / 资源 / sourcemap)
- 代理 /api 到后端
- 完整 TypeScript 配置(env.d.ts + auto-imports.d.ts)