开篇:为什么选择Vite?
Vite就像前端开发的涡轮增压引擎 ——
✅ 闪电启动:基于ESM的按需编译
✅ 热更新神速:HMR速度提升10倍+
✅ 开箱即用:内置TypeScript/SCSS支持
✅ 高度可扩展:插件生态丰富
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [ // 插件配置
vue(), // Vue3单文件组件支持
vueJsx(), // JSX语法支持
],
resolve: {
alias: { // 路径别名
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
proxy: { // API代理配置
'/api': {
target: 'http://localhost:8080',
secure: false,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
plugins: [
vue(), // 必需!解析.vue文件
vueJsx() // 可选!支持JSX语法
]
扩展推荐插件:
import legacy from '@vitejs/plugin-legacy' // 传统浏览器支持
import AutoImport from 'unplugin-auto-import/vite' // 自动导入API
plugins: [
legacy({ targets: ['defaults'] }),
AutoImport({
imports: ['vue', 'vue-router']
})
]
resolve: {
alias: {
'@': '/src', // ❌ 旧版写法(可能不兼容)
'@': fileURLToPath(new URL('./src', import.meta.url)) // ✅ 标准写法
}
}
组件使用示例:
// 传统写法
import Button from '../../../../components/Button.vue'
// 别名写法
import Button from '@/components/Button.vue'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
解决跨域原理图:
浏览器 → 请求/api/user → Vite代理 → 转发到http://localhost:8080/user
// .env.development
VITE_API_BASE = /api
VITE_APP_TITLE = '开发环境'
// vite.config.js
export default defineConfig(({ mode }) => ({
server: {
proxy: {
[import.meta.env.VITE_API_BASE]: {
target: 'http://localhost:8080'
}
}
}
}))
server: {
port: 3000, // 指定端口
https: true, // 启用HTTPS
open: true // 自动打开浏览器
}
build: {
rollupOptions: {
output: {
manualChunks: { // 代码分包策略
lodash: ['lodash-es'],
vue: ['vue', 'vue-router']
}
}
},
chunkSizeWarningLimit: 1000 // ⚠️ 调整块大小警告阈值
}
1️⃣ 安装@types/node:
npm install @types/node --save-dev
2️⃣ 检查tsconfig.json同步配置:
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
当同时使用@vitejs/plugin-legacy和unplugin-auto-import时:
plugins: [
vue(),
AutoImport(), // 放在vue插件之后
legacy() // 放在最后
]
// vite.config.js
export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd())
return {
// 根据环境变量动态配置
base: env.VITE_BASE_URL,
server: {
proxy: { /* 动态代理配置 */ }
}
}
})
server: {
middlewareMode: true, // ️ 启用SSR模式
hmr: { overlay: false }// 禁用HMR覆盖层
}
讨论互动
你在Vite配置中遇到过哪些"玄学"问题?欢迎在评论区分享你的填坑经验!
✨ 小贴士:使用npx vite preview命令可以在生产构建后本地预览打包效果!