一、为什么选 Vite
Vite 用原生 ESM 做开发服务器:改代码毫秒级热更新(HMR),大项目也不卡。构建用 Rollup,产物小、现代。对比 Webpack:
| 对比 |
Vite |
Webpack |
| 开发启动 |
秒级(按需编译) |
分钟级(全量打包) |
| HMR |
快 |
慢 |
| 配置 |
简单 |
复杂 |
| 生态 |
常用插件齐全 |
插件最全 |
二、创建项目
1 2 3 4 5 6 7 8 9
| npm create vite@latest my-app -- --template vue-ts
npm create vite@latest my-app -- --template react-ts
cd my-app npm install npm run dev
|
三、核心配置:别名、代理、环境变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { fileURLToPath, URL } from 'node:url'
export default defineConfig({ plugins: [vue()],
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
server: { port: 5173, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, } } },
build: { outDir: 'dist', sourcemap: false, chunkSizeWarningLimit: 1500 } })
|
tsconfig 也要配别名,否则 TS 报找不到 @/:
1 2 3 4 5 6 7 8
| { "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }
|
四、环境变量
项目根目录放 .env / .env.development / .env.production:
1 2 3 4 5 6 7
| # .env.development VITE_API_BASE=/api VITE_APP_TITLE=开发环境
# .env.production VITE_API_BASE=https://api.example.com VITE_APP_TITLE=生产环境
|
代码里用 import.meta.env 读取(必须以 VITE_ 开头才会暴露):
1 2 3
| const base = import.meta.env.VITE_API_BASE const isProd = import.meta.env.PROD const mode = import.meta.env.MODE
|
五、依赖预构建与分包
Vite 会把第三方依赖预构建缓存到 node_modules/.vite,改依赖版本后残留缓存可能导致奇怪问题,清一下:
1 2
| rm -rf node_modules/.vite npm run dev
|
生产构建分包优化:把体积大的第三方库单独拆 chunk,利用浏览器缓存:
1 2 3 4 5 6 7 8 9 10 11 12
| build: { rollupOptions: { output: { manualChunks: { vue: ['vue', 'vue-router', 'pinia'], echarts: ['echarts'] } } } }
|
更稳妥的方式是用插件自动分析,如 vite-plugin-chunk-split,或直接依赖路由级懒加载产生的天然分包。
六、常用插件
1 2 3
| npm install -D @vitejs/plugin-legacy npm install -D vite-plugin-compression npm install -D unplugin-auto-import
|
1 2 3 4 5 6 7 8 9 10 11 12
| import legacy from '@vitejs/plugin-legacy' import viteCompression from 'vite-plugin-compression'
export default defineConfig({ plugins: [ vue(), legacy({ targets: ['defaults', 'ie >= 11'] }), viteCompression({ algorithm: 'gzip', threshold: 10240 }) ] })
|
unplugin-auto-import 配置后,ref、computed 等 API 无需手动 import,编辑器装插件还能自动补全。
七、部署:静态服务器
Nginx 部署(SPA 刷新 404 处理):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| server { listen 80; root /var/www/myapp/dist; index index.html;
location / { try_files $uri $uri/ /index.html; }
location /assets/ { expires 30d; add_header Cache-Control "public, immutable"; } }
|
常见坑
- 别名配了但 TS 报错:tsconfig 的 paths 没同步,或没重启编辑器/tsc;
- 代理不生效:检查
changeOrigin、目标地址,浏览器缓存也要清;
- 环境变量读不到:确认前缀是
VITE_,且修改 .env 后重启 dev server;
- 构建体积警告:
chunkSizeWarningLimit 只是压制警告,真正要处理的是把大依赖独立分包 + 按需引入。
总结
Vite 的日常套路:别名 + 代理 + 环境变量三件套打底,懒加载 + manualChunks 做分包,插件补齐兼容与压缩。上手比 Webpack 平滑得多,遇到体积问题优先”按需引入 + 独立 chunk”。