基础配置结构
一个典型的 vite.config.js
文件基本结构如下:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
// 基础配置
base: '/',
publicDir: 'public',
// 插件配置
plugins: [vue()],
// 服务器配置
server: {
port: 3000,
open: true
},
// 构建配置
build: {
outDir: 'dist'
}
})
核心配置项详解
1. 开发服务器配置 (server)
server: {
port: 3000, // 指定开发服务器端口
open: true, // 启动时自动打开浏览器
host: true, // 监听所有地址
proxy: { // 代理配置
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
},
hmr: { // 热更新配置
overlay: false // 禁用错误覆盖层
}
}
2. 构建配置 (build)
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
assetsInlineLimit: 4096, // 小于此值的资源将内联为 base64
sourcemap: true, // 生成 source map
minify: 'terser', // 代码压缩方式
terserOptions: { // terser 压缩配置
compress: {
drop_console: true // 移除 console
}
},
rollupOptions: { // Rollup 打包配置
output: {
manualChunks: { // 手动分包
vue: ['vue', 'vue-router', 'pinia']
}
}
}
}
3. 插件系统 (plugins)
Vite 的强大之处在于其丰富的插件生态:
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
import { visualizer } from 'rollup-plugin-visualizer'
plugins: [
vue(), // Vue 支持
legacy({ // 传统浏览器支持
targets: ['defaults', 'not IE 11']
}),
visualizer({ // 包分析工具
open: true,
gzipSize: true
})
]
进阶配置技巧
1. 环境变量处理
import { loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd())
return {
define: {
__APP_VERSION__: JSON.stringify(env.VITE_APP_VERSION)
}
}
})
2. CSS 相关配置
css: {
preprocessorOptions: { // 预处理器配置
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
},
modules: { // CSS Modules 配置
localsConvention: 'camelCase'
},
postcss: { // PostCSS 配置
plugins: [
require('autoprefixer')
]
}
}
3. 路径别名配置
import path from 'path'
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'components': path.resolve(__dirname, './src/components')
}
}
性能优化配置
1. 依赖预构建
optimizeDeps: {
include: ['vue', 'vue-router'],
exclude: ['vue-demi']
}
2. 分包策略
build: {
rollupOptions: {
output: {
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash][extname]',
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor'
}
}
}
}
}
多环境配置实践
// vite.config.prod.js
import { defineConfig } from 'vite'
import baseConfig from './vite.config'
export default defineConfig({
...baseConfig,
build: {
...baseConfig.build,
minify: 'terser',
sourcemap: false
}
})
常见问题解决方案
- 解决跨域问题:使用 server.proxy 配置代理
- 处理静态资源:使用
import.meta.glob
批量导入 - 兼容旧浏览器:使用 @vitejs/plugin-legacy 插件
- 分析打包体积:使用 rollup-plugin-visualizer
总结
Vite 的配置文件虽然简单,但通过合理的配置可以大幅提升开发体验和构建效率。建议根据项目需求逐步调整配置,而不是一次性应用所有优化。记住,最好的配置是适合你项目需求的配置,而不是最复杂的配置。
评论区