Vite 项目配置详解
Vite 是一个现代化的前端构建工具,专为快速开发而设计。以下是 Vite 项目的详细配置指南。
基础配置 (vite.config.js
)
1. 基本框架配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
// https://vitejs.dev/config/
export default defineConfig({
// 项目根目录(相对于当前配置文件)
root: process.cwd(),
// 插件配置
plugins: [vue()],
// 路径解析
resolve: {
// 路径别名
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
'components': fileURLToPath(new URL('./src/components', import.meta.url))
},
// 自动解析的扩展名
extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
},
// 公共基础路径
base: '/',
})
2. 开发服务器配置
export default defineConfig({
server: {
// 服务器端口
port: 5173,
// 自动打开浏览器
open: true,
// 监听所有网络接口
host: true,
// 代理配置
proxy: {
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
},
// 热更新配置
hmr: {
overlay: false // 禁用错误覆盖层
}
}
})
3. 构建配置
export default defineConfig({
build: {
// 输出目录
outDir: 'dist',
// 静态资源目录
assetsDir: 'assets',
// 资源大小限制(警告阈值)
assetsInlineLimit: 4096,
// 是否清空输出目录
emptyOutDir: true,
// 代码分割配置
rollupOptions: {
output: {
// 手动分包
manualChunks: (id) => {
if (id.includes('node_modules')) {
if (id.includes('vue')) {
return 'vue'
}
return 'vendor'
}
},
// 入口文件名格式
entryFileNames: 'js/[name].[hash].js',
// 块文件名格式
chunkFileNames: 'js/[name].[hash].js',
// 资源文件名格式
assetFileNames: 'assets/[name].[hash].[ext]'
}
},
// 最小化配置
minify: 'terser',
// 生成 sourcemap
sourcemap: false
}
})
进阶配置
1. CSS 相关配置
export default defineConfig({
css: {
// 配置 CSS 模块行为
modules: {
scopeBehaviour: 'local',
generateScopedName: '[name]__[local]___[hash:base64:5]'
},
// 预处理器配置
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/variables.scss" as *;`
},
less: {
math: 'always',
globalVars: {
primary: '#1890ff'
}
}
},
// PostCSS 配置
postcss: {
plugins: [
require('autoprefixer'),
require('postcss-pxtorem')({
rootValue: 16,
propList: ['*']
})
]
}
}
})
2. 环境变量配置
import { loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd())
return {
define: {
// 定义全局常量
__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
'process.env': env
},
// 环境变量前缀
envPrefix: 'VITE_'
}
})
3. 常用插件配置
import legacy from '@vitejs/plugin-legacy'
import viteCompression from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'
export default defineConfig({
plugins: [
// 传统浏览器支持
legacy({
targets: ['defaults', 'not IE 11']
}),
// Gzip 压缩
viteCompression({
algorithm: 'gzip',
ext: '.gz'
}),
// 打包分析
visualizer({
open: true,
gzipSize: true,
brotliSize: true
})
]
})
框架特定配置
Vue 项目
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [
vue({
// Vue 特定选项
reactivityTransform: true
}),
// JSX 支持
vueJsx()
]
})
React 项目
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({
// React 特定选项
jsxRuntime: 'automatic'
})
]
})
性能优化
export default defineConfig({
optimizeDeps: {
// 预构建依赖
include: ['vue', 'vue-router', 'pinia'],
// 排除不需要预构建的依赖
exclude: ['vue-demi'],
// 强制预构建
force: true
},
// 构建优化
build: {
// 启用/禁用 CSS 代码拆分
cssCodeSplit: true,
// 启用/禁用 brotli 压缩大小报告
brotliSize: false,
// 块大小警告的限制 (以 kbs 为单位)
chunkSizeWarningLimit: 2000
}
})
完整配置示例
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import viteCompression from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd())
return {
root: process.cwd(),
base: env.VITE_BASE_URL || '/',
plugins: [
vue(),
viteCompression(),
visualizer()
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
port: 5173,
host: true,
open: true,
proxy: {
'/api': {
target: env.VITE_API_BASE_URL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
build: {
outDir: 'dist',
assetsDir: 'assets',
emptyOutDir: true,
rollupOptions: {
output: {
manualChunks: {
vue: ['vue', 'vue-router', 'pinia'],
lodash: ['lodash'],
axios: ['axios']
}
}
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/variables.scss" as *;`
}
}
},
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia']
}
}
})
注意事项
-
确保安装了所有需要的依赖:
npm install -D @vitejs/plugin-vue vite-plugin-compression rollup-plugin-visualizer
-
对于 TypeScript 项目,创建
vite-env.d.ts
文件以获得类型支持:/// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_APP_TITLE: string readonly VITE_API_BASE_URL: string } interface ImportMeta { readonly env: ImportMetaEnv }
-
环境变量应以
VITE_
开头才能在客户端代码中访问 -
对于大型项目,考虑使用
vite-plugin-pages
和vite-plugin-vue-layouts
等插件来优化路由和组织结构
No Comments