配置文件详解
原创2026/9/9...大约 6 分钟
配置文件详解 ⚙️
Vite 的配置文件 vite.config.ts(或 vite.config.js)是项目的"控制中心",所有构建行为都可以在这里自定义。本章我们系统学习配置文件的每一个常用选项。
配置文件基础 💎
文件类型 💎
Vite 支持 TypeScript 与 JavaScript 两种配置方式:
TypeScript(推荐)
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})JavaScript
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})为什么推荐 TypeScript?
- 完整的类型提示
- 编辑器自动补全
- 重构更安全
- Vite 本身使用 TypeScript 开发,与 TypeScript 配合最默契
配置文件查找顺序 👻
Vite 会按以下顺序自动查找配置文件:
vite.config.ts
vite.config.js
vite.config.mjs
vite.config.cjs
vite.config.mts
vite.config.cts显式指定配置文件
vite --config my-vite-config.tsdefineConfig 函数 💎
defineConfig 不仅提供类型提示,还允许传入回调函数实现类型化环境配置:
import { defineConfig } from 'vite'
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
// command: 'build' | 'serve'
// mode: 默认 'development' | 'production',可被 --mode 覆盖
// isSsrBuild: 是否为 SSR 构建
// isPreview: 是否在 vite preview 模式下
if (command === 'serve') {
// 开发环境配置
return {
// dev server 配置
}
} else {
// 生产环境配置
return {
// build 配置
}
}
})完整配置参考 💎
下面是一个综合了所有常用配置的示例:
// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'node:path'
export default defineConfig(({ command, mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd())
return {
// ============ 项目根目录 ============
root: '.', // 项目根目录,默认 process.cwd()
base: '/', // 公共基础路径
publicDir: 'public', // 静态资源目录
cacheDir: 'node_modules/.vite', // 缓存目录
// ============ 插件 ============
plugins: [vue(), vueJsx()],
// ============ 路径别名 ============
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'@components': path.resolve(__dirname, 'src/components'),
'@utils': path.resolve(__dirname, 'src/utils'),
},
extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'],
},
// ============ 开发服务器 ============
server: {
host: '0.0.0.0',
port: 5173,
strictPort: false,
open: true,
cors: true,
hmr: {
overlay: true,
},
proxy: {
'/api': {
target: env.VITE_API_BASE_URL || 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
// ============ 预览服务器 ============
preview: {
host: '0.0.0.0',
port: 4173,
open: true,
},
// ============ CSS 配置 ============
css: {
devSourcemap: true,
modules: {
localsConvention: 'camelCaseOnly',
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`,
},
less: {
math: 'always',
},
},
postcss: {
plugins: [],
},
},
// ============ ESBuild 配置 ============
esbuild: {
target: 'es2020',
jsx: 'automatic',
jsxImportSource: 'vue',
tsconfigRaw: {},
},
// ============ 依赖优化 ============
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia', 'axios'],
exclude: ['your-local-package'],
},
// ============ 构建配置 ============
build: {
target: 'es2020',
outDir: 'dist',
assetsDir: 'assets',
sourcemap: false,
minify: 'esbuild',
cssCodeSplit: true,
cssMinify: 'esbuild',
reportCompressedSize: true,
chunkSizeWarningLimit: 1500,
terserOptions: {},
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
admin: path.resolve(__dirname, 'admin.html'),
},
output: {
entryFileNames: 'assets/[name]-[hash].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash][extname]',
manualChunks: {
vue: ['vue', 'vue-router', 'pinia'],
echarts: ['echarts'],
},
},
},
},
// ============ 性能配置 ============
worker: {
format: 'es',
},
json: {
namedExports: true,
},
experimental: {
renderBuiltUrl: (filename) => {
return `https://cdn.yourcompany.com/${filename}`
},
},
}
})核心配置项详解 💎
base 公共基础路径 👻
export default defineConfig({
// 部署到根路径
base: '/',
// 部署到子路径
base: '/myapp/',
// 相对路径(适合静态文件部署)
base: './',
})部署到子路径时
如果你的应用部署在 https://example.com/myapp/,必须设置 base: '/myapp/',否则静态资源会 404。
resolve.alias 路径别名 👻
import path from 'node:path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'@assets': path.resolve(__dirname, 'src/assets'),
},
},
})需要同步在 tsconfig.json 中配置才能获得类型提示:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@assets/*": ["src/assets/*"]
}
}
}server 开发服务器 👻
export default defineConfig({
server: {
host: '0.0.0.0', // 监听所有地址
port: 5173, // 端口
strictPort: false, // 端口被占用时是否自动切换
open: true, // 自动打开浏览器
cors: true, // 允许跨域
https: false, // 是否启用 https
hmr: {
host: 'localhost',
port: 5173,
protocol: 'ws',
overlay: true, // 错误遮罩
},
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, ''),
// 支持 WebSocket 代理
ws: true,
// 绕过 SSL 校验
secure: false,
},
},
},
})proxy 高级用法
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
configure: (proxy, options) => {
// 代理事件监听
proxy.on('error', (err) => {
console.log('proxy error', err)
})
proxy.on('proxyReq', (proxyReq, req) => {
console.log('Sending Request:', req.url)
})
},
},
// 路径重写:/static -> /public
'/static': {
target: 'http://localhost:3000',
rewrite: (p) => p.replace(/^\/static/, '/public'),
},
}build 构建配置 👻
export default defineConfig({
build: {
// 编译目标
target: 'es2020',
// 输出目录
outDir: 'dist',
assetsDir: 'assets',
// 是否生成 sourcemap
sourcemap: false,
// 压缩方式:'esbuild' | 'terser' | false
minify: 'esbuild',
// CSS 拆分
cssCodeSplit: true,
cssMinify: 'esbuild',
// 多页应用入口
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
// 可以配置多个页面
// admin: path.resolve(__dirname, 'admin.html'),
},
output: {
// 自定义 chunk 拆分
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('vue') || id.includes('pinia')) return 'vue-vendor'
if (id.includes('echarts')) return 'echarts'
if (id.includes('lodash')) return 'lodash'
return 'vendor'
}
},
},
},
// 块大小警告阈值(KB)
chunkSizeWarningLimit: 1500,
// 报告压缩后体积(会拖慢构建,可关闭)
reportCompressedSize: false,
},
})CSS 配置 👻
export default defineConfig({
css: {
// 开发环境是否生成 sourcemap
devSourcemap: true,
// CSS Modules 配置
modules: {
// 默认导出名风格
localsConvention: 'camelCaseOnly', // 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly'
// 类名生成规则
generateScopedName: '[name]__[local]___[hash:base64:5]',
// 全局 CSS Modules
globalModulePaths: [],
},
// CSS 预处理器配置
preprocessorOptions: {
scss: {
// 全局注入代码(每个文件都会包含)
additionalData: `@import "@/styles/variables.scss";`,
// API 版本
api: 'modern-compiler',
},
less: {
math: 'always',
globalVars: {
primary: '#fff',
},
},
},
},
})拆分配置文件 💎
对于大型项目,可以把配置拆成多个文件:
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolveAlias } from './config/alias'
import { resolveServer } from './config/server'
import { resolveBuild } from './config/build'
export default defineConfig(({ command, mode }) => ({
plugins: [vue()],
resolve: resolveAlias(),
server: resolveServer(command, mode),
build: resolveBuild(command, mode),
}))// config/alias.ts
import path from 'node:path'
export const resolveAlias = () => ({
alias: {
'@': path.resolve(__dirname, '../src'),
},
})// config/server.ts
export const resolveServer = (command: string, mode: string) => ({
port: 5173,
host: '0.0.0.0',
// ...
})// config/build.ts
export const resolveBuild = (command: string, mode: string) => ({
outDir: 'dist',
// ...
})环境判断 💎
import { defineConfig } from 'vite'
export default defineConfig(({ command, mode }) => {
const isDev = command === 'serve'
const isProd = command === 'build'
const isTest = mode === 'test'
return {
server: {
// 开发环境才需要 HMR
hmr: isDev,
},
build: {
// 生产环境才生成 sourcemap
sourcemap: isProd,
// 测试环境不压缩
minify: isTest ? false : 'esbuild',
},
}
})在 VSCode 中获得类型提示 💎
安装 Volar 插件,Vite 的所有配置项都会有完整的类型提示和文档悬浮。
推荐插件:
- Volar(Vue 项目的官方推荐)
- TypeScript Vue Plugin(Volar 配套)
- ESLint + Prettier(代码规范)
常见问题 💎
配置不生效 👻
- 检查配置文件名是否正确(
vite.config.ts等) - 检查文件是否在项目根目录
- 配置文件修改后需要重启 Vite
defineConfig必须是默认导出
TypeScript 报错 👻
确保已经安装 vite 依赖(即使只是配置文件也需要),并把 vite.config.ts 加入 tsconfig.json 的 include 中。
修改配置后 dev server 没刷新 👻
某些配置项(如 optimizeDeps、build)需要重启 dev server 才能生效。
小结
本章我们学习了 Vite 配置文件的全部核心内容:
- defineConfig:支持类型提示和回调函数
- 核心配置:base、resolve、server、build、css
- 代理配置:dev server 代理
- 拆分配置:大型项目的最佳实践
- 环境判断:根据 command / mode 区分配置
下一章我们将学习 环境变量与模式。
至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。