最后更新于:2026年7月

还在用 Webpack?是时候升级了。 Vite 以其闪电般的启动速度和热更新,已经成为 2026 年前端构建工具的事实标准。根据 State of JS 2025 调查,Vite 的使用率已经超过 Webpack,成为最受欢迎的构建工具。
但很多人只是「能跑起来」,并没有真正发挥 Vite 的威力。合理的配置和优化可以让构建速度再提升 50%,首屏加载时间减少 30% 以上。
本文从基础配置到生产优化,带你全面掌握 Vite 5。
一、Vite 是什么?
1.1 为什么选择 Vite?
Vite 的核心优势:
| 特性 | 说明 |
|---|---|
| 极快的冷启动 | 基于原生 ESM,不需要打包 |
| 闪电般的 HMR | 热更新毫秒级响应 |
| 丰富的插件 | 兼容 Rollup 插件生态 |
| 开箱即用 | TypeScript、JSX、CSS 等都支持 |
| 优化的构建 | 基于 Rollup,生产构建质量高 |
| 框架无关 | 支持 React、Vue、Svelte 等 |
1.2 Vite vs Webpack vs Rollup
| 维度 | Vite | Webpack | Rollup |
|---|---|---|---|
| 冷启动速度 | ⚡ 秒级 | 🐢 秒-分钟级 | - |
| HMR 速度 | ⚡ 毫秒级 | 🐢 秒级 | - |
| 生产构建 | 基于 Rollup | Webpack 自身 | Rollup |
| 配置复杂度 | 低 | 高 | 中 |
| 生态成熟度 | 高 | 很高 | 高 |
| 学习曲线 | 平缓 | 陡峭 | 中等 |
结论:
- 新项目 → 直接选 Vite
- 老项目迁移 → 评估成本,值得迁移
- 库/组件打包 → Rollup 更专业
1.3 Vite 的工作原理
开发环境:
浏览器 ──原生 ESM──> Vite Dev Server
│
├── 依赖预构建(esbuild)
├── 按需编译
└── HMR(热模块替换)生产环境:
源代码 ──> Rollup ──> 打包输出
│
├── 代码分割
├── Tree Shaking
└── 资源优化二、快速上手
2.1 创建项目
使用 create-vite:
# 使用 npm
npm create vite@latest
# 使用 pnpm(推荐)
pnpm create vite
# 使用 yarn
yarn create vite模板选择:
√ Project name: my-project
√ Select a framework: ...
Vanilla
Vue
React
Preact
Lit
Svelte
Solid
Qwik
...
√ Select a variant: ...
TypeScript
JavaScript
TypeScript + SWC
JavaScript + SWC一键创建 React + TypeScript 项目:
pnpm create vite my-react-app --template react-ts2.2 项目结构
my-project/
├── public/ # 静态资源(不经过构建)
│ └── favicon.ico
├── src/
│ ├── assets/ # 资源文件(会经过构建)
│ ├── App.tsx
│ ├── main.tsx
│ └── index.css
├── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts # Vite 配置文件
└── .gitignore2.3 常用命令
{
"scripts": {
"dev": "vite", # 启动开发服务器
"build": "tsc && vite build", # 生产构建
"preview": "vite preview", # 预览生产构建
"optimize": "vite optimize" # 预构建依赖
}
}三、配置详解
3.1 基础配置
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
// 开发服务器配置
server: {
port: 3000,
open: true,
host: true,
cors: true,
},
// 构建配置
build: {
outDir: 'dist',
sourcemap: true,
minify: 'esbuild',
target: 'es2020',
},
// 路径别名
resolve: {
alias: {
'@': '/src',
'@components': '/src/components',
'@utils': '/src/utils',
},
},
});3.2 路径别名配置
Vite 配置:
// vite.config.ts
import path from 'path';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils'),
'@hooks': path.resolve(__dirname, './src/hooks'),
'@types': path.resolve(__dirname, './src/types'),
},
},
});TypeScript 配置(tsconfig.json):
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"],
"@hooks/*": ["src/hooks/*"],
"@types/*": ["src/types/*"]
}
}
}3.3 环境变量配置
环境变量文件:
.env # 所有环境
.env.local # 所有环境(本地覆盖,不提交到 git)
.env.development # 开发环境
.env.production # 生产环境
.env.staging # 预发布环境使用环境变量:
// .env
VITE_APP_TITLE = My App
VITE_API_URL = https://api.example.com
// 代码中使用
console.log(import.meta.env.VITE_APP_TITLE);
console.log(import.meta.env.VITE_API_URL);注意: 只有以 VITE_ 开头的变量才会暴露到客户端代码中。
智能提示:
// src/vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_APP_TITLE: string;
readonly VITE_API_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}3.4 代理配置
// vite.config.ts
export default defineConfig({
server: {
proxy: {
// 简单代理
'/api': 'http://localhost:3001',
// 带选项的代理
'/api2': {
target: 'http://localhost:3002',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api2/, ''),
},
// WebSocket 代理
'/ws': {
target: 'ws://localhost:3003',
ws: true,
},
},
},
});四、插件生态
4.1 常用插件推荐
| 插件 | 用途 | 推荐度 |
|---|---|---|
| @vitejs/plugin-react | React 支持 | ⭐⭐⭐⭐⭐ |
| @vitejs/plugin-vue | Vue 支持 | ⭐⭐⭐⭐⭐ |
| @vitejs/plugin-legacy | 旧浏览器兼容 | ⭐⭐⭐⭐ |
| vite-plugin-compression | gzip/brotli 压缩 | ⭐⭐⭐⭐ |
| vite-plugin-imagemin | 图片压缩 | ⭐⭐⭐⭐ |
| vite-plugin-pwa | PWA 支持 | ⭐⭐⭐⭐ |
| vite-plugin-svg-icons | SVG 图标管理 | ⭐⭐⭐ |
| rollup-plugin-visualizer | 打包分析 | ⭐⭐⭐⭐⭐ |
| unplugin-auto-import | 自动导入 | ⭐⭐⭐⭐ |
| unplugin-vue-components | 组件自动注册 | ⭐⭐⭐⭐ |
4.2 插件配置示例
图片压缩:
import { defineConfig } from 'vite';
import imagemin from 'vite-plugin-imagemin';
export default defineConfig({
plugins: [
imagemin({
gifsicle: { optimizationLevel: 7, interlaced: false },
optipng: { optimizationLevel: 7 },
mozjpeg: { quality: 80 },
pngquant: { quality: [0.8, 0.9] },
svgo: {
plugins: [
{ name: 'removeViewBox', active: false },
],
},
}),
],
});Gzip/Brotli 压缩:
import { defineConfig } from 'vite';
import viteCompression from 'vite-plugin-compression';
export default defineConfig({
plugins: [
viteCompression({
verbose: true,
disable: false,
threshold: 10240, // 10KB 以上的文件才压缩
algorithm: 'gzip',
ext: '.gz',
}),
// Brotli 压缩(压缩率更高)
viteCompression({
verbose: true,
threshold: 10240,
algorithm: 'brotliCompress',
ext: '.br',
}),
],
});打包分析:
import { defineConfig } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
plugins: [
visualizer({
open: true,
filename: 'dist/stats.html',
gzipSize: true,
brotliSize: true,
}),
],
});自动导入:
import { defineConfig } from 'vite';
import AutoImport from 'unplugin-auto-import/vite';
export default defineConfig({
plugins: [
AutoImport({
imports: [
'react',
'react-router-dom',
{
'react-i18next': ['useTranslation', 't'],
},
],
dts: 'src/auto-imports.d.ts',
eslintrc: {
enabled: true,
},
}),
],
});五、开发环境优化
5.1 依赖预构建优化
// vite.config.ts
export default defineConfig({
optimizeDeps: {
// 强制预构建依赖
include: [
'react',
'react-dom',
'react-router-dom',
'axios',
'lodash-es',
],
// 排除预构建(让 ESM 包直接被浏览器加载)
exclude: ['some-esm-only-package'],
// 预构建时的 esbuild 配置
esbuildOptions: {
target: 'es2020',
},
},
});什么时候需要手动配置 include?
- 动态导入的依赖
- 被转换为 ESM 的 CommonJS 包
- 依赖有很多导出(如 lodash)
5.2 加速开发服务器
// vite.config.ts
export default defineConfig({
server: {
// 启用 HTTP/2(需要证书)
https: false,
// 预热常用文件,减少首次加载时间
warmup: {
clientFiles: ['./src/main.tsx', './src/App.tsx'],
},
// 文件系统监听配置
watch: {
usePolling: true, // Docker/WSL 环境需要
interval: 1000,
},
},
});5.3 CSS 处理优化
// vite.config.ts
export default defineConfig({
css: {
// CSS Modules 配置
modules: {
localsConvention: 'camelCase',
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
// PostCSS 配置
postcss: {
plugins: [
// Autoprefixer(自动加前缀)
require('autoprefixer'),
// CSS 嵌套
require('postcss-nesting'),
],
},
// 预处理器配置
preprocessorOptions: {
scss: {
additionalData: `
@import "@/styles/variables.scss";
@import "@/styles/mixins.scss";
`,
},
less: {
javascriptEnabled: true,
modifyVars: {
'primary-color': '#1890ff',
},
},
},
},
});5.4 Tailwind CSS 配置
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
});// tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./index.html',
'./src/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {
colors: {
primary: '#3b82f6',
},
},
},
plugins: [],
};/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;六、生产构建优化
6.1 构建配置优化
// vite.config.ts
export default defineConfig({
build: {
// 输出目录
outDir: 'dist',
assetsDir: 'assets',
// 目标浏览器
target: 'es2020',
// 压缩方式:esbuild(快)| terser(压缩率更高,但慢)
minify: 'esbuild',
// 生成 source map
sourcemap: false, // 生产环境关闭
// 代码分割策略
rollupOptions: {
output: {
// 手动分包
manualChunks: {
// React 相关
'react-vendor': ['react', 'react-dom', 'react-router-dom'],
// UI 库
'antd-vendor': ['antd', '@ant-design/icons'],
// 工具库
'utils-vendor': ['lodash-es', 'dayjs', 'axios'],
},
// 静态资源文件名
assetFileNames: 'assets/[name].[hash][extname]',
chunkFileNames: 'assets/[name].[hash].js',
entryFileNames: 'assets/[name].[hash].js',
},
},
// 大于此大小的 chunk 会警告
chunkSizeWarningLimit: 500, // KB
// 构建时清空目录
emptyOutDir: true,
// 启用 CSS 代码分割
cssCodeSplit: true,
},
});6.2 代码分割策略
策略 1:按路由分割(最常用)
// 使用 React.lazy + Suspense
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}策略 2:按功能分割
// vite.config.ts
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
// 框架核心
framework: ['react', 'react-dom', 'react-router-dom'],
// UI 组件库
ui: ['antd', '@ant-design/icons'],
// 数据请求
data: ['axios', 'react-query'],
// 图表
charts: ['echarts', 'react-echarts'],
// 富文本编辑器
editor: ['@tiptap/react', '@tiptap/starter-kit'],
},
},
},
},
});策略 3:智能分包(vite-plugin-chunk-split)
import { defineConfig } from 'vite';
import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
export default defineConfig({
plugins: [
chunkSplitPlugin({
strategy: 'default',
customSplitting: {
'react-vendor': [/react/, /react-dom/],
'antd-vendor': [/antd/],
'utils-vendor': [/lodash/, /dayjs/],
},
}),
],
});6.3 资源优化
图片优化:
// 使用 vite-plugin-imagemin
import imagemin from 'vite-plugin-imagemin';
export default defineConfig({
plugins: [
imagemin({
// 只在生产环境启用
...(process.env.NODE_ENV === 'production'
? {
gifsicle: { optimizationLevel: 7 },
optipng: { optimizationLevel: 7 },
mozjpeg: { quality: 80 },
pngquant: { quality: [0.8, 0.9] },
svgo: { plugins: [{ name: 'removeViewBox', active: false }] },
}
: {}),
}),
],
});字体优化:
/* 使用 font-display: swap 避免阻塞渲染 */
@font-face {
font-family: 'Inter';
src: url('/fonts/inter.woff2') format('woff2');
font-display: swap;
}SVG 优化:
// 使用 vite-plugin-svgr 导入 SVG 为组件
import Logo from '@/assets/logo.svg?react';
function Header() {
return <Logo className="w-6 h-6" />;
}6.4 Tree Shaking 优化
确保被 Tree Shaking:
// ✅ 好:使用具名导出(可以被 Tree Shaking)
export const foo = () => {
console.log('foo');
};
export const bar = () => {
console.log('bar');
};
// ❌ 不好:使用默认导出对象(无法被 Tree Shaking)
export default {
foo: () => console.log('foo'),
bar: () => console.log('bar'),
};sideEffects 配置(package.json):
{
"sideEffects": [
"*.css",
"*.scss",
"src/polyfill.js"
]
}七、性能分析与监控
7.1 打包分析
# 安装
pnpm add -D rollup-plugin-visualizer// vite.config.ts
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
plugins: [
visualizer({
open: true,
filename: 'dist/stats.html',
gzipSize: true,
brotliSize: true,
template: 'treemap', // treemap | sunburst | network
}),
],
});# 构建并生成分析报告
pnpm build
# 自动打开 stats.html7.2 开发环境性能
查看预构建依赖:
# 手动运行预构建
vite optimize --force
# 查看预构建缓存位置
# macOS: ~/Library/Caches/vite
# Linux: ~/.cache/vite
# Windows: %TEMP%/viteHMR 性能优化:
// vite.config.ts
export default defineConfig({
server: {
hmr: {
// 减少 HMR 日志
overlay: true,
},
},
// 优化依赖预构建
optimizeDeps: {
include: [
// 把常用依赖加入预构建
'react',
'react-dom',
'antd',
'axios',
],
},
});7.3 Lighthouse 性能审计
关键指标:
| 指标 | 目标 | 说明 |
|---|---|---|
| LCP | < 2.5s | 最大内容绘制 |
| FID | < 100ms | 首次输入延迟 |
| CLS | < 0.1 | 累积布局偏移 |
| FCP | < 1.8s | 首次内容绘制 |
| TTI | < 3.8s | 可交互时间 |
优化方向:
- 减少首屏资源体积
- 懒加载非关键资源
- 优化图片和字体
- 使用 CDN 加速
八、高级配置技巧
8.1 多环境配置
// vite.config.ts
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(({ mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd(), '');
return {
plugins: [react()],
server: {
port: parseInt(env.VITE_PORT || '3000'),
proxy: {
'/api': {
target: env.VITE_API_BASE_URL,
changeOrigin: true,
},
},
},
build: {
sourcemap: mode !== 'production',
minify: mode === 'production' ? 'esbuild' : false,
},
};
});8.2 多页面应用
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
export default defineConfig({
plugins: [react()],
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
admin: resolve(__dirname, 'admin/index.html'),
docs: resolve(__dirname, 'docs/index.html'),
},
},
},
});项目结构:
├── index.html
├── admin/
│ └── index.html
├── docs/
│ └── index.html
└── src/8.3 库模式
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
export default defineConfig({
plugins: [react()],
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
name: 'MyLib',
formats: ['es', 'umd', 'cjs'],
fileName: (format) => `my-lib.${format}.js`,
},
rollupOptions: {
// 外部化依赖(不打包进库)
external: ['react', 'react-dom'],
output: {
// UMD 格式的全局变量
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
},
},
});8.4 SSR 配置
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
ssr: {
// 不打包的依赖(保持 require)
external: ['some-cjs-only-package'],
// 强制打包的依赖
noExternal: ['some-esm-package'],
},
});九、常见问题与解决方案
Q1:Vite 启动慢怎么办?
排查方向:
- 依赖太多? → 优化
optimizeDeps.include - 文件太多? → 检查是否有不必要的文件被监听
- 使用了 WSL/Docker? → 开启
usePolling - 插件太多? → 禁用不必要的插件
优化方案:
// vite.config.ts
export default defineConfig({
optimizeDeps: {
// 把大依赖加入预构建
include: ['antd', 'lodash', 'echarts'],
},
server: {
// 预热常用文件
warmup: {
clientFiles: ['./src/main.tsx', './src/App.tsx'],
},
// WSL/Docker 环境
watch: {
usePolling: true,
},
},
});Q2:HMR 不生效怎么办?
常见原因:
- 组件没有默认导出 → 检查文件导出
- 使用了高阶组件 → 确保 HOC 正确处理
- 文件名大小写问题 → 统一大小写规范
- 循环依赖 → 解决循环依赖问题
调试方法:
# 开启调试日志
DEBUG=vite:hmr vite devQ3:构建后页面空白怎么办?
排查步骤:
- 控制台报错? → 查看错误信息
- 路径不对? → 检查
base配置 - 资源加载失败? → 检查网络请求
- 浏览器兼容? → 检查
build.target
// 部署在子路径时需要配置 base
export default defineConfig({
base: '/my-app/',
});Q4:打包体积太大怎么办?
优化步骤:
1. 分析打包体积
└── rollup-plugin-visualizer
2. 代码分割
├── 路由级分割(React.lazy)
├── 手动分包(manualChunks)
└── 动态导入
3. 资源优化
├── 图片压缩
├── 字体优化
└── SVG 优化
4. 依赖优化
├── Tree Shaking
├── 替换大依赖
└── 按需加载
5. 压缩与缓存
├── Gzip/Brotli 压缩
└── CDN 缓存Q5:Vite 和 Webpack 怎么选?
| 项目类型 | 推荐 | 原因 |
|---|---|---|
| 新项目 | Vite | 速度快,体验好 |
| 老项目(Webpack) | 评估迁移 | 收益大于成本就迁 |
| 复杂企业级应用 | Vite 或 Webpack | 都能满足,看团队 |
| 库/组件开发 | Vite + Rollup | Vite 开发,Rollup 构建 |
| 微前端 | 都可以 | 看具体方案 |
十、总结
Vite 优化清单
- 配置路径别名,提升开发体验
- 配置环境变量和代理
- 优化依赖预构建(optimizeDeps)
- 配置代码分割(路由级 + 手动分包)
- 启用图片压缩
- 启用 Gzip/Brotli 压缩
- 配置 Tree Shaking
- 优化 CSS(PostCSS、Tailwind)
- 配置打包分析工具
- 配置 Lighthouse 性能监控
Vite 学习路径
第 1 周:基础使用
- 创建项目
- 基础配置
- 常用命令
第 2 周:进阶配置
- 插件使用
- 环境变量
- 路径别名
- 代理配置
第 3-4 周:性能优化
- 代码分割
- 资源优化
- 构建分析
- 性能监控
第 2 个月:高级用法
- 库模式
- SSR
- 自定义插件
- 多环境配置【相关推荐】
- React 19 + TypeScript 完全指南 - 前端框架
- AI 编程助手横向对比 - AI 辅助编程
- Docker Compose 实战指南 - 容器化部署
Vite 不仅仅是一个构建工具,它代表了现代前端开发的新范式。掌握 Vite 的配置和优化,你的项目开发体验和产品性能都会上一个台阶。祝你构建愉快!⚡
