Vite 配置
vite.config.ts
Vite 配置文件位于项目根目录,支持使用 defineConfig 获得类型提示。
完整配置模板
ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig(({ mode, command }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
// 基础路径(生产环境静态资源路径)
base: env.VITE_PUBLIC_PATH || '/',
// 插件
plugins: [vue()],
// 路径解析
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
extensions: ['.js', '.ts', '.vue', '.json'],
},
// 开发服务器
server: {
host: true,
port: 5173,
open: true,
https: false,
proxy: {
'/api': {
target: env.VITE_API_URL,
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, ''),
},
},
},
// 构建配置
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: false,
cssCodeSplit: true,
minify: 'esbuild',
chunkSizeWarningLimit: 1500,
rollupOptions: {
output: {
manualChunks: {
vue: ['vue'],
vendor: ['axios'],
},
},
},
},
// CSS 预处理
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/styles/global.scss";',
},
},
},
// 依赖优化
optimizeDeps: {
include: ['axios'],
exclude: ['your-lib'],
},
}
})import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig(({ mode, command }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
// 基础路径(生产环境静态资源路径)
base: env.VITE_PUBLIC_PATH || '/',
// 插件
plugins: [vue()],
// 路径解析
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
extensions: ['.js', '.ts', '.vue', '.json'],
},
// 开发服务器
server: {
host: true,
port: 5173,
open: true,
https: false,
proxy: {
'/api': {
target: env.VITE_API_URL,
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, ''),
},
},
},
// 构建配置
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: false,
cssCodeSplit: true,
minify: 'esbuild',
chunkSizeWarningLimit: 1500,
rollupOptions: {
output: {
manualChunks: {
vue: ['vue'],
vendor: ['axios'],
},
},
},
},
// CSS 预处理
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/styles/global.scss";',
},
},
},
// 依赖优化
optimizeDeps: {
include: ['axios'],
exclude: ['your-lib'],
},
}
})路径别名(resolve.alias)
ts
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'components': path.resolve(__dirname, 'src/components'),
}
}resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'components': path.resolve(__dirname, 'src/components'),
}
}ESM 写法(推荐):
ts
import { fileURLToPath, URL } from 'node:url'
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
}import { fileURLToPath, URL } from 'node:url'
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
}使用:
ts
import Button from '@/components/Button.vue'
// 代替: import Button from '../../components/Button.vue'import Button from '@/components/Button.vue'
// 代替: import Button from '../../components/Button.vue'代理配置(server.proxy)
用于开发环境解决跨域问题:
ts
server: {
proxy: {
'/api': {
target: 'http://localhost:8080', // 后端地址
changeOrigin: true, // 修改请求头 origin
rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径
},
// 匹配所有路径
'/': {
target: 'http://localhost:3000',
changeOrigin: true,
}
}
}server: {
proxy: {
'/api': {
target: 'http://localhost:8080', // 后端地址
changeOrigin: true, // 修改请求头 origin
rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径
},
// 匹配所有路径
'/': {
target: 'http://localhost:3000',
changeOrigin: true,
}
}
}原理: 请求 /api/user/info → 转发到 http://localhost:8080/user/info(rewrite 去掉了 /api 前缀)
环境变量
.env 文件
| 文件 | 用途 |
|---|---|
.env | 所有模式加载 |
.env.development | 仅开发模式 |
.env.production | 仅生产模式 |
.env.local | 所有模式,被 git 忽略 |
示例 .env.development:
VITE_API_URL=http://localhost:8080
VITE_PUBLIC_PATH=/VITE_API_URL=http://localhost:8080
VITE_PUBLIC_PATH=/只有
VITE_前缀的变量会暴露给客户端代码
在配置中使用 loadEnv
ts
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
// 参数1: 当前模式 参数2: env 目录 参数3: 前缀过滤(''=全部)
return {
base: env.VITE_PUBLIC_PATH,
server: {
proxy: {
'/api': { target: env.VITE_API_URL, changeOrigin: true }
}
}
}
})export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
// 参数1: 当前模式 参数2: env 目录 参数3: 前缀过滤(''=全部)
return {
base: env.VITE_PUBLIC_PATH,
server: {
proxy: {
'/api': { target: env.VITE_API_URL, changeOrigin: true }
}
}
}
})在代码中使用
ts
console.log(import.meta.env.VITE_API_URL)
console.log(import.meta.env.MODE) // 'development' | 'production'
console.log(import.meta.env.DEV) // true / false
console.log(import.meta.env.PROD) // true / false
console.log(import.meta.env.BASE_URL) // base pathconsole.log(import.meta.env.VITE_API_URL)
console.log(import.meta.env.MODE) // 'development' | 'production'
console.log(import.meta.env.DEV) // true / false
console.log(import.meta.env.PROD) // true / false
console.log(import.meta.env.BASE_URL) // base path构建配置(build)
ts
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
sourcemap: false, // 关闭 source map
cssCodeSplit: true, // 按组件分割 CSS
minify: 'esbuild', // 'esbuild'(快) | 'terser'(更小)
chunkSizeWarningLimit: 1500, // 分包警告阈值(KB)
rollupOptions: {
output: {
manualChunks: {
vue: ['vue'],
vendor: ['axios', 'lodash'],
},
},
},
}build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
sourcemap: false, // 关闭 source map
cssCodeSplit: true, // 按组件分割 CSS
minify: 'esbuild', // 'esbuild'(快) | 'terser'(更小)
chunkSizeWarningLimit: 1500, // 分包警告阈值(KB)
rollupOptions: {
output: {
manualChunks: {
vue: ['vue'],
vendor: ['axios', 'lodash'],
},
},
},
}CSS 配置
ts
css: {
// 模块化
modules: {
localsConvention: 'camelCase',
},
// 预处理器
preprocessorOptions: {
scss: {
additionalData: '@import "@/styles/variables.scss";',
},
less: {
javascriptEnabled: true,
},
},
// PostCSS(或使用 postcss.config.js)
postcss: {
plugins: [autoprefixer],
},
}css: {
// 模块化
modules: {
localsConvention: 'camelCase',
},
// 预处理器
preprocessorOptions: {
scss: {
additionalData: '@import "@/styles/variables.scss";',
},
less: {
javascriptEnabled: true,
},
},
// PostCSS(或使用 postcss.config.js)
postcss: {
plugins: [autoprefixer],
},
}依赖优化(optimizeDeps)
ts
optimizeDeps: {
include: ['react', 'react-dom', 'lodash-es'], // 强制预构建
exclude: ['my-local-package'], // 排除预构建
force: false, // 强制重新优化
disabled: false, // 禁用('build' | 'dev')
}optimizeDeps: {
include: ['react', 'react-dom', 'lodash-es'], // 强制预构建
exclude: ['my-local-package'], // 排除预构建
force: false, // 强制重新优化
disabled: false, // 禁用('build' | 'dev')
}Vite 8 配置变更
从 Vite 7 升级到 Vite 8:
ts
export default defineConfig({
build: {
// ❌ Vite 1-7
// rollupOptions: { ... }
// ✅ Vite 8
rolldownOptions: {
output: {
manualChunks: {
'react-vendor': ['react', 'react-dom'],
},
},
},
// 新增内置功能
license: { fileName: 'licenses.json' }, // 许可证信息
manifest: true, // 生成 manifest.json
},
// TS 路径别名自动读取
resolve: {
tsconfigPaths: true, // 无需额外插件!
},
})export default defineConfig({
build: {
// ❌ Vite 1-7
// rollupOptions: { ... }
// ✅ Vite 8
rolldownOptions: {
output: {
manualChunks: {
'react-vendor': ['react', 'react-dom'],
},
},
},
// 新增内置功能
license: { fileName: 'licenses.json' }, // 许可证信息
manifest: true, // 生成 manifest.json
},
// TS 路径别名自动读取
resolve: {
tsconfigPaths: true, // 无需额外插件!
},
})
Cao Note