vite.config.js
是 Vite 项目的核心配置文件,可自定义项目构建、开发服务器和插件等行为。以下是对该文件的详细解析和实战案例:
一、配置文件基础结构
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' // 以 React 项目为例
import path from 'path'
export default defineConfig({
// 项目根目录(index.html 文件所在的位置)
root: process.cwd(),
// 开发环境和生产环境的公共基础路径
base: '/',
// 开发服务器配置
server: {
port: 3000,
open: true, // 自动打开浏览器
proxy: {
// 代理配置示例
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
// 构建配置
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
sourcemap: false, // 是否生成源映射
minify: 'terser', // 压缩工具
terserOptions: {
compress: {
drop_console: true, // 生产环境移除 console
drop_debugger: true // 生产环境移除 debugger
}
}
},
// 插件配置
plugins: [react()],
// 解析配置
resolve: {
alias: {
// 路径别名配置
'@': '/src'
}
},
// CSS 配置
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "./src/styles/variables.scss";` // 全局引入 SCSS 变量
}
}
}
})
二、核心配置项详解
1. 开发服务器配置(server)
server: {
port: 3000, // 开发服务器端口
host: '0.0.0.0', // 监听所有地址,包括局域网和公网地址
https: false, // 是否启用 HTTPS
open: true, // 启动时自动打开浏览器
cors: true, // 启用 CORS
proxy: {
// 配置代理解决跨域问题
'/api': {
target: 'http://backend-api.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
timeout: 10000, // 请求超时时间
configure: (proxy, options) => {
// 自定义代理配置
proxy.on('error', (err, req, res) => {
console.log('Proxy error:', err)
})
}
}
}
}
2. 构建配置(build)
build: {
target: 'esnext', // 目标浏览器版本
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
assetsInlineLimit: 4096, // 小于此阈值的资源会被内联为 base64
chunkSizeWarningLimit: 500, // 分块大小警告阈值(KB)
rollupOptions: {
// Rollup 打包选项
output: {
manualChunks(id) {
// 自定义分块策略
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
}
}
}
}
3. 路径别名配置(resolve.alias)
resolve: {
alias: {
'@': path.resolve(__dirname, './src'), // 将 @ 映射到 src 目录
'@components': path.resolve(__dirname, './src/components'), // 组件目录别名
'utils': path.resolve(__dirname, './src/utils') // 工具函数目录别名
}
}
4. 环境变量配置(env)
envDir: './env', // 环境变量文件目录
envPrefix: 'VITE_', // 以 VITE_ 开头的变量会被加载到客户端
5. 插件配置(plugins)
plugins: [
react(), // React 支持
vue(), // Vue 支持
svgLoader(), // SVG 加载器
legacyPlugin({ // 传统浏览器支持
targets: ['ie >= 11'],
additionalLegacyPolyfills: ['regenerator-runtime/runtime']
}),
// 条件加载插件
process.env.NODE_ENV === 'production' ? compressPlugin() : null
]
三、实战案例
1. 基于环境的条件配置
export default defineConfig(({ command, mode }) => {
if (command === 'serve') {
// 开发环境配置
return {
server: {
proxy: {
'/api': 'http://localhost:8080'
}
}
}
} else {
// 生产环境配置
return {
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true
}
}
}
}
}
})
2. 自定义 HTML 注入
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
plugins: [
{
name: 'html-transform',
transformIndexHtml(html) {
return html.replace(/%APP_TITLE%/g, env.APP_TITLE)
}
}
]
}
})
3. 自定义 CSS 处理
css: {
modules: {
localsConvention: 'camelCaseOnly', // 类名转换为驼峰
generateScopedName: '[name]__[local]___[hash:base64:5]' // 自定义生成类名
},
postcss: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: ['last 2 versions', '> 1%']
})
]
}
}
四、常见问题与解决方案
1. 处理静态资源路径问题
// 在 CSS 中使用相对路径
background-image: url('./assets/image.png');
// 或使用 import 导入
import imgUrl from './assets/image.png';
2. 优化生产环境构建
build: {
brotliSize: false, // 不生成 brotli 压缩文件
emptyOutDir: true, // 构建前清空输出目录
sourcemap: process.env.NODE_ENV === 'development' // 仅开发环境生成源映射
}
3. 解决跨域请求问题
server: {
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
headers: {
'X-Forwarded-For': '127.0.0.1'
}
}
}
}
五、推荐插件
- Vue 支持:
@vitejs/plugin-vue
- React 支持:
@vitejs/plugin-react
- TypeScript 支持:内置支持,无需额外插件
- SVG 处理:
vite-plugin-svg-loader
- 压缩插件:
vite-plugin-compression
- PWA 支持:
vite-plugin-pwa
- 环境变量注入:
vite-plugin-env-compatible
通过合理配置 vite.config.js
,可以显著提升开发体验和生产环境性能。建议根据项目需求选择性使用上述配置,并参考 Vite 官方文档 获取更多详细信息。