Vite 的配置文件结构清晰,主要涵盖项目根目录、开发服务器、模块解析、构建、CSS处理等核心配置项。
📁 核心配置项概览
为了让配置项更一目了然,这里将主要配置信息汇总如下:
· 项目根目录与基础路径
· 配置项: root, base
· 主要作用: 设定项目的起点和公共部署路径。
· 开发服务器配置
· 配置项: server
· 主要作用: 设置端口、代理、主机等开发服务器行为。
· 模块解析与路径
· 配置项: resolve
· 主要作用: 配置路径别名,简化模块导入。
· 构建与输出
· 配置项: build
· 主要作用: 控制打包输出目录、压缩、代码分割等构建行为。
· CSS与预处理器
· 配置项: css
· 主要作用: 配置 CSS 模块化、Sass/Less 等预处理器。
· 插件管理
· 配置项: plugins
· 主要作用: 扩展 Vite 功能,如支持 Vue、React 框架。
· 依赖优化
· 配置项: optimizeDeps
· 主要作用: 预构建依赖以提升冷启动速度。
· 全局变量
· 配置项: define
· 主要作用: 定义在构建时被替换的全局常量。
🔧 详细配置说明
- 路径别名 (resolve.alias)
设置 @/ 指向 src/ 目录是常见做法。你需要从 path 模块引入 resolve 方法。
typescript
import { resolve } from 'path';
export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
'@components': resolve(__dirname, 'src/components')
},
// 还可配置省略扩展名列表
extensions: ['.js', '.ts', '.vue', '.json']
}
});
这让你可以用 import HelloWorld from '@/components/HelloWorld.vue'; 代替相对路径。
- 开发服务器与代理 (server)
解决开发时的跨域问题。
typescript
export default defineConfig({
server: {
port: 8080, // 自定义端口[citation:3][citation:10]
host: '0.0.0.0', // 允许局域网访问[citation:3][citation:9]
open: true, // 启动时自动打开浏览器[citation:3][citation:10]
proxy: { // 代理配置
'/api': {
target: 'http://your-backend-api.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '') // 可重写路径[citation:6][citation:9]
}
}
}
});
- 环境变量
· 加载时机:Vite 会在配置加载完成之后才读取 .env 文件。因此,如果配置项(如 server.port)依赖环境变量,需要手动加载。
· 手动加载:使用 loadEnv 函数。
typescript
import { defineConfig, loadEnv } from 'vite';
export default defineConfig(({ mode }) => { // mode 来自脚本命令
const env = loadEnv(mode, process.cwd(), ''); // 加载所有环境变量
return {
define: {
__APP_ENV__: JSON.stringify(env.APP_ENV)
},
server: {
port: env.VITE_PORT ? Number(env.VITE_PORT) : 5173 // 条件设置
}
};
});
· 客户端暴露:默认只有以 VITE_ 开头的变量才会暴露给客户端,通过 import.meta.env.VITE_XXX 访问。如需修改前缀,可使用 envPrefix 选项。
- CSS 预处理器 (css.preprocessorOptions)
typescript
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/variables.scss" as *;` // 全局注入变量或 mixin[citation:6][citation:10]
},
less: {
math: 'always',
globalVars: { '@primary-color': '#1890ff' }
}
}
}
});
- 构建选项 (build)
typescript
export default defineConfig({
build: {
outDir: 'dist', // 输出目录[citation:6]
assetsDir: 'assets', // 静态资源子目录[citation:6][citation:10]
sourcemap: true, // 生成 source map 便于调试[citation:9][citation:10]
minify: 'terser', // 代码压缩方式,可选 'esbuild' 或 'terser'[citation:9]
rollupOptions: { // 底层 Rollup 配置[citation:6]
input: { // 多页面应用入口[citation:6][citation:7]
main: resolve(__dirname, 'index.html'),
admin: resolve(__dirname, 'admin.html')
},
output: { // 代码分割策略
manualChunks: {
vendor: ['vue', 'vue-router']
}
}
}
}
});
- 框架插件 (plugins)
根据你的技术栈选择。
typescript
// Vue 3
import vue from '@vitejs/plugin-vue';
// React
import react from '@vitejs/plugin-react';
// 或 react-swc (速度更快)
import reactSwc from '@vitejs/plugin-react-swc';
export default defineConfig({
plugins: [vue()] // 或 [react()] / [reactSwc()]
});
📄 完整配置示例(Vue 3 + TypeScript)
以下是整合了上述常见配置的完整 vite.config.ts 示例:
typescript
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
// 手动加载环境变量
const env = loadEnv(mode, process.cwd(), '');
return {
// 项目根目录与公共路径
root: process.cwd(),
base: env.VITE_PUBLIC_PATH || '/',
// 插件
plugins: [vue()],
// 开发服务器
server: {
host: '0.0.0.0',
port: env.VITE_PORT ? Number(env.VITE_PORT) : 5173,
open: true,
proxy: {
'/api': {
target: env.VITE_API_BASE_URL || 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
// 模块解析
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
'@components': resolve(__dirname, 'src/components')
},
extensions: ['.js', '.ts', '.jsx', '.tsx', '.vue', '.json']
},
// 构建配置
build: {
outDir: 'dist',
assetsDir: 'static/assets',
sourcemap: mode !== 'production', // 生产环境不生成 sourcemap
minify: 'terser',
rollupOptions: {
output: {
chunkFileNames: 'static/js/[name]-[hash].js',
entryFileNames: 'static/js/[name]-[hash].js',
assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
}
}
},
// CSS 预处理器
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
},
// 依赖优化
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia'],
exclude: ['some-excluded-dep']
},
// 全局常量定义
define: {
__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
__APP_ENV__: JSON.stringify(mode)
}
};
});
💡 高级与实用技巧
· 条件配置:导出函数,根据 command (开发 serve / 构建 build) 或 mode (环境模式) 返回不同配置。
typescript
export default defineConfig(({ command, mode }) => {
if (command === 'serve') return { /* 开发配置 */ };
else return { /* 生产配置 */ };
});
· 配置智能提示:使用 defineConfig 可获得完整的 TypeScript 类型提示。
· 异步配置:若配置需要异步获取,可导出异步函数。
typescript
export default defineConfig(async () => {
const data = await fetchConfig();
return { /* 配置 */ };
});
· 调试配置文件:在 VS Code 中调试配置文件,有时会遇到断点位置不匹配。你可以尝试调整 .vscode/settings.json 来解决。
这份指南涵盖了从基础到进阶的核心配置。如果你有特定场景的配置需求,比如 SSR(服务端渲染) 或 构建为库,可以告诉我,我能提供更具体的指引。