Vite配置指南
完整vite.config.ts模板
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
plugins: [
react(),
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@hooks': path.resolve(__dirname, './src/hooks'),
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
build: {
outDir: 'dist',
sourcemap: mode === 'development',
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
router: ['react-router-dom'],
},
},
},
chunkSizeWarningLimit: 600,
},
define: {
__APP_VERSION__: JSON.stringify(env.npm_package_version),
},
}
})
环境变量
# .env (all modes) VITE_API_URL=https://api.example.com VITE_APP_TITLE=My App # .env.development VITE_API_URL=http://localhost:8080 # .env.production VITE_API_URL=https://api.prod.com # Access in code (only VITE_ prefix exposed to client) const apiUrl = import.meta.env.VITE_API_URL
常用Vite插件
| 插件 | 用途 |
|---|---|
| @vitejs/plugin-react | React快速刷新 |
| @vitejs/plugin-vue | Vue 3支持 |
| vite-plugin-pwa | PWA/Service Worker |
| unplugin-auto-import | API自动导入 |
| vite-bundle-visualizer | 包大小分析 |
| @vitejs/plugin-legacy | 旧浏览器支持 |