为什么写这篇:Vite 5+ 在 2023 年起成为新项目默认;Vite 6(2024-11)性能再次飞跃;Vite 7(2025-06)支持 Rolldown 实验性打包器。本文用最新 Vite 7 + React/Vue + TS 走通完整工程化流程,附带 monorepo 实战。
适用读者:要从 Webpack 迁到 Vite 的工程师;想给新项目选 Vite 的负责人;想用 Vite 7 最新特性(Rolldown / 环境变量)的中高级前端。
前置知识:会用 npm/pnpm;了解 React 或 Vue 基础;知道 TypeScript 是什么。
目录
- Vite 是什么
- 环境要求
- 创建 Vite 项目:5 种模板
- 项目结构详解
- Vite 核心配置文件
- TypeScript 集成
- 路径别名 @ 配置
- 反向代理与 HMR
- 多环境变量 .env 管理
- 生产构建:Rollup 与 Rolldown 实验
- 代码风格:ESLint + Prettier
- VSCode 必装插件
- Monorepo + pnpm workspace 实战
- Vite vs Webpack 性能对比
- 常见排错
1. Vite 是什么
Vite(法语"快"的发音 /vit/)是下一代前端构建工具,由 Vue 作者尤雨溪团队开发。核心目标:让开发体验更快、更顺手。
1.1 核心特性
| 特性 | 说明 |
|---|
| 极速冷启动 | 开发模式不打包,按需 ESM 编译 |
| 毫秒级 HMR | 修改文件只更新该模块,不重新加载页面 |
| 开箱即用 TS / JSX / CSS 预处理器 | 零配置支持 |
| 生产用 Rollup 打包 | 产物优化、Tree Shaking、代码分割 |
| 生态完整 | Vue / React / Svelte / Solid / Preact 全支持 |
| 插件体系 | 兼容 Rollup 插件、自动兼容大多数 Webpack 插件 |
1.2 为什么快:传统 vs Vite
1
2
3
4
5
6
7
| 传统 Webpack 模式(dev):
启动 ── 打包所有模块 ── 才能 serve
Vite 模式(dev):
启动 ── 立即 serve ── 浏览器按需请求 ESM
↑
浏览器原生 import 解析,服务器只编译被请求的文件
|
原理:现代浏览器都支持 <script type="module"> + 原生 ESM 导入。Vite 把"打包"这件事推迟到浏览器运行时——服务器只编译被请求的单个文件,完全跳过冷启动的全量打包。
2. 环境要求
| 工具 | 版本 | 备注 |
|---|
| Node.js | 20.19+ 或 22.12+ | Vite 7 强制要求 |
| pnpm(推荐) | 9+ | 装包快、磁盘省 |
| npm | 10+ | Node 自带 |
| yarn | 4+ | Berry 系列 |
1
2
| node -v # v20.19.0 或 v22.12.0+
pnpm -v # 9.x
|
不兼容旧 Node:Vite 7 不再支持 Node 18.x。
3. 创建 Vite 项目:5 种模板
3.1 命令行创建
交互式:
1
2
3
4
5
| ✔ Project name: … react-ts-demo1
✔ Select a framework: › React
✔ Select a variant: › TypeScript
✔ Use rolldown-vite (Experimental)?: no
✔ Install with pnpm and start now?: yes
|
跑完自动启动:
1
2
3
4
5
| VITE v7.2.7 ready in 339 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
|
3.2 直接指定模板
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # React + TS
pnpm create vite react-ts-demo --template react-ts
# Vue 3 + TS
pnpm create vite vue3-ts-demo --template vue-ts
# Svelte
pnpm create vite svelte-demo --template svelte-ts
# 原生 JS
pnpm create vite vanilla-demo --template vanilla
# 列出所有模板
pnpm create vite --help
|
3.3 Rolldown-Vite 实验性选项
Vite 7 实验性接入 Rolldown——基于 Rust 的下一代打包器,目标是替换 esbuild + Rollup,实现极致构建速度。
- 问:Use rolldown-vite (Experimental)?: no → 目前不建议生产用
- 实验性质,可能与某些插件不兼容
- 实际收益:5-10x 打包速度提升(仅生产模式)
4. 项目结构详解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| react-ts-demo1/
├── dist/ # 构建产物
├── node_modules/
├── public/ # 不参与构建的静态资源
│ └── vite.svg
├── src/
│ ├── assets/ # 静态资源(被 webpack/vite 处理)
│ │ └── react.svg
│ ├── components/ # 公共组件
│ ├── App.tsx # 根组件
│ ├── main.tsx # 入口
│ ├── App.css
│ ├── index.css # 全局样式入口
│ └── vite-env.d.ts # Vite 内置类型
├── .gitignore
├── eslint.config.js # ESLint 9 扁平配置
├── index.html # 入口 HTML
├── package.json
├── pnpm-lock.yaml # 必须提交
├── README.md
├── tsconfig.app.json # 应用代码 TS 配置
├── tsconfig.json # TS 根配置
├── tsconfig.node.json # Node 环境 TS 配置
└── vite.config.ts # Vite 配置
|
tsconfig 拆三份:Vite 模板默认把 TS 配置拆成 tsconfig.app.json(业务代码)和 tsconfig.node.json(vite.config.ts),用 references 关联。
5. Vite 核心配置文件
vite.config.ts:
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
35
36
37
38
39
40
41
| import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from 'path'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
server: {
port: 8080,
host: '127.0.0.1',
open: true,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, '')
}
}
},
build: {
target: 'es2020',
sourcemap: false,
outDir: 'dist',
rollupOptions: {
output: {
manualChunks: {
react: ['react', 'react-dom'],
router: ['react-router-dom'],
ui: ['antd']
}
}
}
}
})
|
6. TypeScript 集成
Vite 自动支持 .ts / .tsx / .vue 文件——不需要 ts-loader / babel-loader。
1
2
3
4
5
6
7
8
9
10
11
| // vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_APP_TITLE: string
readonly VITE_API_BASE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
|
读环境变量:
1
2
3
| console.log(import.meta.env.VITE_API_BASE)
console.log(import.meta.env.MODE) // 'development' | 'production'
console.log(import.meta.env.DEV) // boolean
|
7. 路径别名 @ 配置
7.1 vite.config.ts
1
2
3
4
5
6
7
8
9
10
| import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
}
})
|
7.2 tsconfig.json(必须配,否则 TS 找不到)
1
2
3
4
5
6
7
8
| {
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
|
之后就能 import Foo from '@/components/Foo'。
8. 反向代理与 HMR
8.1 代理后端 API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, '')
},
'/socket.io': {
target: 'http://localhost:3000',
ws: true, // 支持 WebSocket
changeOrigin: true
}
}
}
|
8.2 HMR 配置
1
2
3
4
5
6
7
| server: {
hmr: {
host: '127.0.0.1',
port: 8080,
overlay: true // 错误时全屏遮罩
}
}
|
8.3 在 React 中接受 HMR
1
2
3
4
5
6
7
8
9
10
| // main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
)
|
Vite 自动通过 import.meta.hot 注入 HMR API,不需要额外配置——React Fast Refresh 自动接管。
9. 多环境变量 .env 管理
Vite 默认只有 development 和 production。要扩展:
1
2
3
4
| .env # 所有环境都加载
.env.development # npm run dev 加载
.env.test # npm run build --mode test 加载
.env.production # npm run build --mode production 加载
|
9.1 .env.development
1
2
| VITE_APP_TITLE = '开发环境'
VITE_API_BASE = '/api'
|
9.2 .env.production
1
2
| VITE_APP_TITLE = '生产环境'
VITE_API_BASE = 'https://api.example.com'
|
9.3 package.json scripts
1
2
3
4
5
6
7
8
9
| {
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"build:test": "tsc --noEmit && vite build --mode test",
"build:prod": "tsc --noEmit && vite build --mode production",
"preview": "vite preview"
}
}
|
必须 VITE_ 开头才能被 import.meta.env 识别——防止意外暴露服务端配置。
10. 生产构建:Rollup 与 Rolldown 实验
10.1 默认 Rollup 打包
1
2
3
4
5
6
7
| pnpm build
# vite v7.2.7 building for production...
# ✓ 1234 modules transformed.
# dist/index.html 0.45 kB
# dist/assets/index-abc123.js 312.50 kB │ gzip: 102.40 kB
# dist/assets/index-def456.css 45.20 kB │ gzip: 12.10 kB
# ✓ built in 5.42s
|
10.2 关键选项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| build: {
target: 'es2020', // 目标浏览器
outDir: 'dist',
sourcemap: false, // 生产不开
minify: 'esbuild', // 默认 esbuild,可换 terser
cssCodeSplit: true, // CSS 拆分
chunkSizeWarningLimit: 1500, // 块大小警告阈值
rollupOptions: {
output: {
manualChunks: { /* 拆包 */ },
entryFileNames: 'assets/[name].[hash].js',
chunkFileNames: 'assets/[name].[hash].js',
assetFileNames: 'assets/[name].[hash][extname]'
}
}
}
|
10.3 启用 Rolldown 实验
升级到 Vite 7 + 安装 Rolldown Vite:
1
| pnpm add rolldown-vite -D
|
目前不建议生产用——某些插件还不兼容。
11. 代码风格:ESLint + Prettier
11.1 ESLint 9 扁平配置(vite create 自动生成)
eslint.config.js:
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
| import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': 'warn'
}
}
)
|
11.2 Prettier
1
| pnpm add -D prettier eslint-config-prettier
|
.prettierrc.json:
1
2
3
4
5
6
7
8
| {
"printWidth": 100,
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"endOfLine": "auto"
}
|
12. VSCode 必装插件
| 插件 | 用途 |
|---|
| ESLint | 9+ 扁平配置支持 |
| Prettier | 自动格式化 |
| TypeScript Vue Plugin (Volar) | Vue 3 + TS |
| ES7+ React/Redux snippets | React 代码片段 |
| Tailwind CSS IntelliSense | Tailwind 类名补全 |
| Path Intellisense | 路径补全 |
| Stylelint | CSS/Less/SCSS 检查 |
13. Monorepo + pnpm workspace 实战
13.1 pnpm-workspace.yaml
1
2
3
| packages:
- 'apps/*'
- 'packages/*'
|
13.2 apps/web/package.json
1
2
3
4
5
6
7
8
9
10
11
12
| {
"name": "@myorg/web",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build"
},
"dependencies": {
"@myorg/utils": "workspace:*",
"@myorg/ui": "workspace:*"
}
}
|
13.3 packages/utils/package.json
1
2
3
4
5
6
7
8
9
| {
"name": "@myorg/utils",
"version": "1.0.0",
"type": "module",
"main": "./src/index.ts",
"exports": {
".": "./src/index.ts"
}
}
|
13.4 跨包引用
1
2
3
| // apps/web/src/App.tsx
import { formatDate } from '@myorg/utils'
import { Button } from '@myorg/ui'
|
1
2
3
| pnpm install # 装所有工作区依赖 + 链接
pnpm -F @myorg/web dev # 只跑 web 包的 dev
pnpm -r build # 所有包 build
|
14. Vite vs Webpack 性能对比
| 维度 | Vite 7 | Webpack 5 |
|---|
| 冷启动 | < 1s(按需编译) | 10-30s(全量打包) |
| HMR 速度 | < 100ms | 1-5s |
| 生产构建 | Rollup,5-15s | 30s-2min |
| 配置复杂度 | 零配置 + 少量 plugins | 大量 loader + plugin |
| 生态兼容 | Rollup 插件 + 大量 Vite 插件 | Webpack 生态(成熟) |
| SSR 支持 | 强(Vite SSR API) | 中(webpack-ssr-plugin) |
| 学习曲线 | 平缓 | 陡峭 |
2025 选型:
- 新项目:直接 Vite(启动快、配置简单)
- 老 Webpack 项目:不必强迁——Webpack 5 + 持久化缓存已经够快
- 大厂 monorepo:评估 Rspack(Rust 编写、Webpack 兼容 API)—— 字节跳动 + Microsoft 在用
15. 常见排错
15.1 TS2307: Cannot find module ‘./App.vue’
解法:建 src/vite-env.d.ts(Vite 模板已自动生成):
1
2
3
4
5
6
| /// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
|
15.2 import path 找不到
检查清单:
vite.config.ts 配了 aliastsconfig.json 配了 paths(两端必须都配)- 重启 VSCode(让 TS 服务重读 tsconfig)
15.3 代理 404
1
2
3
4
5
6
7
| proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
// rewrite: (p) => p.replace(/^\/api/, '') // ⚠️ 注释掉,看后端路由
}
}
|
先看 dev server 真正发到哪——加 bypass: (req) => req.url 在 proxy 里打印。
15.4 端口被占用
1
2
3
4
5
6
7
| # Windows
netstat -ano | findstr :8080
taskkill /PID <pid> /F
# macOS / Linux
lsof -i :8080
kill -9 <pid>
|
或改 Vite 配置:
1
2
3
4
| server: {
port: 8081, // 换个端口
strictPort: false // 端口被占时自动换
}
|
小结
Vite 7 是 2025 年前端构建工具的"事实标准":
- 极快冷启动(< 1s)—— 跳过 dev 模式的全量打包
- TypeScript / JSX / CSS 预处理器零配置
@ 路径别名两行配置- 多环境变量
.env.development / .env.production - 生产 Rollup 打包,可选 Rolldown 实验(更快)
- monorepo 配合 pnpm workspace 一行
pnpm -r build 跑所有包
下一步:学 Vite 插件开发(写自己的 plugin)、Vite SSR(配合 React 19 RSC / Vue 3 Nuxt)、微前端(Vite + Module Federation)。
参考资料