一、为什么选 Vite

Vite 用原生 ESM 做开发服务器:改代码毫秒级热更新(HMR),大项目也不卡。构建用 Rollup,产物小、现代。对比 Webpack:

对比 Vite Webpack
开发启动 秒级(按需编译) 分钟级(全量打包)
HMR 快 慢
配置 简单 复杂
生态 常用插件齐全 插件最全

二、创建项目

1
2
3
4
5
6
7
8
9
# Vue3 + TS
npm create vite@latest my-app -- --template vue-ts

# React + 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
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'

export default defineConfig({
plugins: [vue()],

// 路径别名:@/ 指向 src/
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},

// 开发代理:/api 转发到后端,绕过跨域
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
// rewrite: (path) => path.replace(/^\/api/, '')
}
}
},

// 生产构建
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 // development / production

五、依赖预构建与分包

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
// vite.config.ts
build: {
rollupOptions: {
output: {
// 手动分包:三方库独立 chunk
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 # 生产 gzip 预压缩
npm install -D unplugin-auto-import # API 自动导入(ref 不用手动 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(),
// 兼容不支持 ESM 的旧浏览器(会额外打一份系统包)
legacy({ targets: ['defaults', 'ie >= 11'] }),
// 构建时预生成 .gz 文件,配合 Nginx gzip_static 直接生效
viteCompression({ algorithm: 'gzip', threshold: 10240 })
]
})

unplugin-auto-import 配置后,ref、computed 等 API 无需手动 import,编辑器装插件还能自动补全。

七、部署:静态服务器

1
npm run build   # 产物在 dist/

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;
}

# 带 hash 的静态资源长缓存
location /assets/ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}

常见坑

  1. 别名配了但 TS 报错:tsconfig 的 paths 没同步,或没重启编辑器/tsc;
  2. 代理不生效:检查 changeOrigin、目标地址,浏览器缓存也要清;
  3. 环境变量读不到:确认前缀是 VITE_,且修改 .env 后重启 dev server;
  4. 构建体积警告:chunkSizeWarningLimit 只是压制警告,真正要处理的是把大依赖独立分包 + 按需引入。

总结

Vite 的日常套路:别名 + 代理 + 环境变量三件套打底,懒加载 + manualChunks 做分包,插件补齐兼容与压缩。上手比 Webpack 平滑得多,遇到体积问题优先”按需引入 + 独立 chunk”。