Vite 构建工具完全指南 2026

💡 什么是 Vite? Vite 是新一代前端构建工具,由 Vue.js 作者尤雨溪开发。它利用浏览器原生 ES 模块支持,实现了极速的开发服务器启动和热更新,生产环境则使用 Rollup 进行打包。Vite 的出现,彻底改变了前端开发的体验。
本文将带你从 0 到 1 掌握 Vite:
- ✅ Vite 核心原理与优势
- ✅ 项目创建与基础配置
- ✅ 常用功能与插件使用
- ✅ 性能优化最佳实践
- ✅ 生产构建与部署
- ✅ 从 Webpack 迁移指南
- ✅ 常见问题与解决方案
一、Vite 基础
1.1 为什么选择 Vite
传统构建工具(如 Webpack)在开发时需要打包整个应用,项目越大,启动越慢。Vite 从根本上改变了这一模式。
| 特性 | Vite | Webpack | 说明 |
|---|---|---|---|
| 启动速度 | ⚡ 毫秒级 | 🐢 秒级甚至分钟级 | Vite 无需打包,按需编译 |
| 热更新速度 | ⚡ 即时更新 | 🐢 随项目增大变慢 | Vite 只更新变更模块 |
| 构建速度 | ⚡ Rollup 驱动 | 🐢 较慢 | Rollup 比 Webpack 更快 |
| 配置复杂度 | 📝 简单 | 📝📝📝 复杂 | Vite 开箱即用 |
| 生态成熟度 | 📦 快速增长 | 📦📦📦 非常成熟 | Webpack 生态更丰富 |
| ESM 支持 | ✅ 原生支持 | ⚠️ 需要配置 | Vite 基于 ESM 设计 |
1.2 Vite 核心原理
开发环境:
- 利用浏览器原生 ES Modules 支持
- 启动时不打包,按需编译文件
- 模块热替换(HMR)在原生 ESM 上执行
- 预构建依赖,提升页面加载速度
生产环境:
- 使用 Rollup 打包代码
- 高度优化的输出
- 支持代码分割、Tree Shaking 等
💡 关键区别: Webpack 是「先打包,再服务」;Vite 是「先服务,按需编译」。
1.3 浏览器支持
- 开发环境: 支持原生 ESM 的现代浏览器(Chrome 61+、Firefox 60+、Safari 11+、Edge 16+)
- 生产环境: 通过配置可支持到传统浏览器(需要 @vitejs/plugin-legacy)
二、快速开始
2.1 环境要求
- Node.js: 18+ 或 20+(推荐 LTS 版本)
- 包管理器: npm / yarn / pnpm(推荐 pnpm)
- 操作系统: Windows / macOS / Linux
# 检查 Node.js 版本
node -v
# 如果版本过低,使用 nvm 升级
nvm install --lts
nvm use --lts2.2 创建项目
npm create vite@latestyarn create vitepnpm create vitebun create vite交互式创建流程:
# 1. 输入项目名
Project name: my-vite-app
# 2. 选择框架
Select a framework:
Vanilla
Vue
React
Preact
Lit
Svelte
Solid
Qwik
React TypeScript
Vue TypeScript
...
# 3. 选择语言变体
Select a variant:
JavaScript
TypeScript
TypeScript + SWC
# 4. 完成创建,进入项目并运行
cd my-vite-app
npm install
npm run dev命令行直接创建:
# 创建 Vue 3 + TypeScript 项目
npm create vite@latest my-vue-app -- --template vue-ts
# 创建 React + TypeScript 项目
npm create vite@latest my-react-app -- --template react-ts
# 可用模板:vanilla, vue, react, preact, lit, svelte, solid
# 加 -ts 后缀为 TypeScript 版本2.3 项目结构
my-vite-app/
├── node_modules/ # 依赖包
├── public/ # 静态资源(不参与构建)
│ └── favicon.ico
├── src/ # 源码目录
│ ├── assets/ # 资源文件
│ ├── components/ # 组件
│ ├── App.vue # 根组件
│ ├── main.js # 入口文件
│ └── style.css # 全局样式
├── index.html # HTML 入口
├── package.json # 项目配置
├── vite.config.js # Vite 配置
└── .gitignore2.4 常用命令
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 本地预览生产构建
npm run preview
# 运行开发服务器并指定端口
npm run dev -- --port 3000
# 构建并输出分析报告
npm run build -- --report三、核心配置
3.1 配置文件
Vite 使用 vite.config.js(或 .ts)作为配置文件:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
// 开发服务器配置
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
// 构建配置
build: {
outDir: 'dist',
sourcemap: true,
minify: 'esbuild'
},
// 路径别名
resolve: {
alias: {
'@': '/src'
}
}
})3.2 路径别名配置
// vite.config.js
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils')
}
}
})如果使用 TypeScript,还需要在 tsconfig.json 中配置:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
}
}3.3 开发服务器配置
export default defineConfig({
server: {
// 端口号
port: 3000,
// 启动时自动打开浏览器
open: true,
// 主机名(设置为 0.0.0.0 可被外部访问)
host: '0.0.0.0',
// 严格端口(端口被占用时直接退出)
strictPort: false,
// HTTPS 配置
https: false,
// 代理配置
proxy: {
// 字符串简写
'/api': 'http://localhost:8080',
// 完整配置
'/api2': {
target: 'http://localhost:8081',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api2/, '')
},
// WebSocket 代理
'/socket.io': {
target: 'ws://localhost:3001',
ws: true
}
},
// CORS
cors: true,
// 自定义响应头
headers: {
'X-Custom-Header': 'Vite'
}
}
})3.4 环境变量
Vite 使用 dotenv 加载环境变量,变量需要以 VITE_ 前缀开头才会暴露到客户端。
.env 文件:
.env # 所有环境加载
.env.local # 所有环境加载(git 忽略)
.env.development # 开发环境
.env.production # 生产环境
.env.staging # 预发布环境示例 .env.development:
# 只有 VITE_ 前缀的变量才会暴露给前端
VITE_API_BASE_URL=http://localhost:3000/api
VITE_APP_TITLE=My App (Development)
# 这个变量不会暴露给前端(服务器端可用)
DB_PASSWORD=secret123代码中使用:
console.log(import.meta.env.VITE_API_BASE_URL)
console.log(import.meta.env.VITE_APP_TITLE)
// 内置变量
console.log(import.meta.env.MODE) // 模式:development/production
console.log(import.meta.env.DEV) // 是否开发环境
console.log(import.meta.env.PROD) // 是否生产环境
console.log(import.meta.env.SSR) // 是否 SSRTypeScript 类型支持:
// src/vite-env.d.ts
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_APP_TITLE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}四、资源处理
4.1 静态资源
public 目录: 放在 public 目录的文件会被原样复制到输出目录,不参与构建。
public/
robots.txt
favicon.ico
images/
logo.png引用方式:
<!-- 直接用根路径引用 -->
<img src="/images/logo.png" />src/assets 目录: 放在 src 中的资源会被 Vite 处理(哈希、压缩等)。
// 直接导入
import logo from './assets/logo.png'
// 在 CSS 中使用
.logo {
background: url('./assets/logo.png');
}4.2 CSS 处理
Vite 原生支持 CSS、CSS Modules、Sass/Less/Stylus。
CSS Modules:
/* Button.module.css */
.button {
padding: 8px 16px;
border-radius: 4px;
}
.primary {
background: blue;
color: white;
}import styles from './Button.module.css'
function Button() {
return <button className={`${styles.button} ${styles.primary}`}>Click</button>
}CSS 预处理器:
# 安装 Sass
npm install -D sass
# 安装 Less
npm install -D less
# 安装 Stylus
npm install -D stylus// vite.config.js
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
}
})PostCSS 配置:
Vite 自动应用 PostCSS 配置,创建 postcss.config.js 即可:
export default {
plugins: {
'postcss-px-to-viewport-8-plugin': {
viewportWidth: 375
},
autoprefixer: {}
}
}4.3 JSON 处理
// 导入整个 JSON
import data from './data.json'
// 具名导入(Tree Shaking)
import { name, version } from './data.json'4.4 Web Workers
// 普通导入
import MyWorker from './worker?worker'
const worker = new MyWorker()五、插件系统
5.1 常用插件
| 插件 | 功能 |
|---|---|
| @vitejs/plugin-vue | Vue 3 支持 |
| @vitejs/plugin-react | React 支持 |
| @vitejs/plugin-legacy | 传统浏览器支持 |
| @vitejs/plugin-basic-ssl | HTTPS 开发证书 |
| vite-plugin-pwa | PWA 支持 |
| unplugin-auto-import | 自动导入 API |
| unplugin-vue-components | 自动注册组件 |
| vite-plugin-compression | gzip/br 压缩 |
| rollup-plugin-visualizer | 包大小分析 |
5.2 Vue 插件配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [
vue({
// 响应性语法糖
reactivityTransform: true
}),
vueJsx()
]
})5.3 React 插件配置
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()]
})5.4 自动导入插件
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts'
}),
Components({
dirs: ['src/components'],
dts: 'src/components.d.ts'
})
]
})5.5 开发自己的插件
// my-plugin.js
export default function myPlugin() {
return {
name: 'my-plugin',
// 构建开始时
buildStart() {
console.log('Build started')
},
// 转换代码
transform(code, id) {
if (id.endsWith('.custom.js')) {
return {
code: code.replace('__PLACEHOLDER__', 'replaced'),
map: null
}
}
},
// 构建结束
buildEnd() {
console.log('Build ended')
}
}
}六、性能优化
6.1 依赖预构建
Vite 会自动预构建依赖,提升页面加载速度。
export default defineConfig({
optimizeDeps: {
// 强制预构建的依赖
include: ['lodash-es', 'dayjs'],
// 排除预构建的依赖
exclude: ['some-esm-package'],
// 自定义 esbuild 配置
esbuildOptions: {
target: 'es2020'
}
}
})6.2 构建优化
export default defineConfig({
build: {
// 输出目录
outDir: 'dist',
// 资源目录
assetsDir: 'assets',
// 源码映射
sourcemap: false,
// 压缩方式:esbuild | terser | false
minify: 'esbuild',
// chunk 大小警告(单位 KB)
chunkSizeWarningLimit: 500,
// Rollup 配置
rollupOptions: {
output: {
// 代码分割策略
manualChunks: {
vendor: ['vue', 'vue-router', 'pinia'],
utils: ['lodash-es', 'dayjs']
},
// 静态资源文件名
chunkFileNames: 'assets/js/[name]-[hash].js',
entryFileNames: 'assets/js/[name]-[hash].js',
assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
}
},
// 小于此大小的资源内联为 base64(单位 KB)
assetsInlineLimit: 4096
}
})6.3 打包分析
# 安装 rollup-plugin-visualizer
npm install -D rollup-plugin-visualizerimport { visualizer } from 'rollup-plugin-visualizer'
export default defineConfig({
plugins: [
visualizer({
open: true,
filename: 'dist/stats.html'
})
]
})6.4 图片压缩
npm install -D vite-plugin-imageminimport viteImagemin from 'vite-plugin-imagemin'
export default defineConfig({
plugins: [
viteImagemin({
gifsicle: { optimizationLevel: 7 },
optipng: { optimizationLevel: 7 },
mozjpeg: { quality: 80 },
pngquant: { quality: [0.8, 0.9] },
svgo: {
plugins: [{ name: 'removeViewBox' }]
}
})
]
})七、生产构建与部署
7.1 构建命令
# 构建生产版本
npm run build
# 预览构建结果
npm run preview
# 预览时指定端口
npm run preview -- --port 80807.2 传统浏览器兼容
如果需要支持 IE11 等旧浏览器:
npm install -D @vitejs/plugin-legacyimport legacy from '@vitejs/plugin-legacy'
export default defineConfig({
plugins: [
legacy({
targets: ['defaults', 'not IE 11'],
additionalLegacyPolyfills: ['regenerator-runtime/runtime']
})
]
})7.3 部署到静态托管
Nginx 配置:
server {
listen 80;
server_name your-domain.com;
root /var/www/dist;
index index.html;
# SPA 路由回退
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}GitHub Pages 部署:
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run build
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./distVercel 部署:
直接连接 GitHub 仓库,Vercel 会自动检测 Vite 项目并部署。
Netlify 部署:
创建 netlify.toml:
[build]
command = "npm run build"
publish = "dist"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200八、从 Webpack 迁移
8.1 主要差异
| 功能 | Webpack | Vite |
|---|---|---|
| 配置文件 | webpack.config.js | vite.config.js |
| 开发服务器 | webpack-dev-server | vite dev server |
| 模块系统 | CommonJS + ESM | 原生 ESM |
| 打包工具 | webpack | Rollup(生产) |
| 热更新 | 整个模块重打包 | 精确到组件 |
8.2 迁移步骤
1. 创建 Vite 配置文件
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
},
extensions: ['.mjs', '.js', '.ts', '.vue', '.json']
},
server: {
port: 8080,
proxy: {
'/api': 'http://localhost:3000'
}
}
})2. 更新入口 HTML
Vite 使用 index.html 作为入口:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>3. 更新 package.json 脚本
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}4. 处理 require 语法
Vite 不支持 require(),需要改为 import:
// 旧写法
const lodash = require('lodash')
// 新写法
import lodash from 'lodash'5. 环境变量适配
// Webpack
process.env.VUE_APP_API_URL
// Vite
import.meta.env.VITE_API_URL九、常见问题
9.1 开发相关
Q: 启动后局域网无法访问?
// vite.config.js
export default defineConfig({
server: {
host: '0.0.0.0'
}
})Q: 代理不生效?
检查路径匹配和 changeOrigin 设置:
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}9.2 构建相关
Q: 打包后路径不对?
设置正确的 base:
export default defineConfig({
// 部署在根路径
base: '/',
// 部署在子路径
base: '/my-app/'
})Q: 打包体积太大?
- 使用
rollup-plugin-visualizer分析 - 配置
manualChunks拆分代码 - 开启 Tree Shaking
- 使用 CDN 加载大型库
9.3 依赖相关
Q: 某些依赖报错?
可能是依赖预构建的问题,尝试手动添加:
export default defineConfig({
optimizeDeps: {
include: ['problematic-package']
}
})十、总结与速查
10.1 核心命令速查
# 创建项目
pnpm create vite
# 开发
pnpm dev
pnpm dev --port 3000
pnpm dev --host 0.0.0.0
# 构建
pnpm build
pnpm build --watch
# 预览
pnpm preview
pnpm preview --port 808010.2 配置速查
export default defineConfig({
// 基础路径
base: '/',
// 插件
plugins: [],
// 路径别名
resolve: { alias: {} },
// 开发服务器
server: { port: 3000, proxy: {} },
// 构建配置
build: { outDir: 'dist', sourcemap: false },
// CSS 配置
css: { preprocessorOptions: {} },
// 依赖预构建
optimizeDeps: { include: [] }
})10.3 Vite 生态系统
- VitePress: 静态站点生成器(本站使用)
- Nuxt 3: Vue 全栈框架(基于 Vite)
- SvelteKit: Svelte 全栈框架
- Astro: 内容驱动的静态站点
- Qwik City: Qwik 全栈框架
相关文章推荐:
🎯 Vite 已经成为现代前端开发的标准配置,掌握它能让你的开发效率提升数倍。从今天开始,体验极速开发的乐趣吧!