以下是更详细的 Vite 配置指南,涵盖了更多高级配置项和实际应用场景,帮助您全面掌握 Vite 的配置能力。
1. 安装与初始化
使用以下命令创建 Vite 项目:
npm create vite@latest
# 或
yarn create vite
选择框架(如 Vue、React)和模板后,Vite 会自动生成项目结构。
2. 项目结构
典型的 Vite 项目结构如下:
my-vite-project/
├── public/ # 静态资源(直接复制到输出目录)
├── src/ # 源代码
│ ├── assets/ # 静态资源(如图片、字体)
│ ├── components/ # 组件
│ ├── styles/ # 全局样式
│ ├── App.vue # 根组件
│ └── main.js # 入口文件
├── index.html # 入口 HTML 文件
├── vite.config.js # Vite 配置文件
├── package.json # 项目依赖
└── .env # 环境变量文件
3. Vite 配置文件 (vite.config.js
)
Vite 的配置文件支持 JavaScript 或 TypeScript。以下是一个更全面的配置示例:
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue'; // Vue 插件
import react from '@vitejs/plugin-react'; // React 插件
import { fileURLToPath, URL } from 'node:url'; // 处理路径
import legacy from '@vitejs/plugin-legacy'; // 兼容旧版浏览器
import { visualizer } from 'rollup-plugin-visualizer'; // 构建分析工具
export default defineConfig(({ mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd(), '');
return {
// 插件配置
plugins: [
vue(), // Vue 插件
react(), // React 插件
legacy({ // 兼容旧版浏览器
targets: ['defaults', 'not IE 11'],
}),
visualizer({ // 构建分析
open: true,
filename: 'bundle-analysis.html',
}),
],
// 开发服务器配置
server: {
port: 3000, // 端口号
open: true, // 自动打开浏览器
proxy: { // 代理配置
'/api': {
target: env.VITE_API_BASE_URL || 'http://localhost:5000', // 代理目标
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
cors: true, // 启用 CORS
hmr: { // 热模块替换配置
overlay: true,
},
},
// 构建配置
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
sourcemap: true, // 生成 sourcemap
minify: 'terser', // 代码压缩工具
terserOptions: { // Terser 配置
compress: {
drop_console: true, // 移除 console.log
drop_debugger: true, // 移除 debugger
},
},
rollupOptions: { // Rollup 配置
output: {
manualChunks: { // 手动分块
vendor: ['vue', 'vue-router', 'axios'], // 第三方库单独打包
},
},
},
},
// 路径别名
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)), // 路径别名
},
extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue'], // 自动解析扩展名
},
// CSS 配置
css: {
preprocessorOptions: { // 预处理器配置
scss: {
additionalData: `@import "@/styles/variables.scss";`, // 全局引入 SCSS 变量
},
less: {
modifyVars: { // 修改 Less 变量
'primary-color': '#1890ff',
},
javascriptEnabled: true,
},
},
modules: { // CSS Modules 配置
localsConvention: 'camelCase',
},
},
// 环境变量配置
envPrefix: 'VITE_', // 环境变量前缀
define: { // 全局变量替换
__APP_VERSION__: JSON.stringify(env.npm_package_version),
},
// 优化配置
optimizeDeps: {
include: ['vue', 'vue-router', 'axios'], // 预构建依赖
exclude: ['some-package'], // 排除依赖
},
};
});
4. 常用配置项详解
插件配置 (plugins
)
@vitejs/plugin-vue
:Vue 支持。@vitejs/plugin-react
:React 支持。@vitejs/plugin-legacy
:为旧版浏览器提供支持。rollup-plugin-visualizer
:构建分析工具。
开发服务器配置 (server
)
port
:指定开发服务器端口。open
:是否自动打开浏览器。proxy
:配置代理,解决跨域问题。cors
:启用跨域资源共享。hmr
:热模块替换配置。
构建配置 (build
)
outDir
:指定构建输出目录。assetsDir
:静态资源存放目录。sourcemap
:是否生成 sourcemap 文件。minify
:代码压缩工具,可选terser
或esbuild
。rollupOptions
:Rollup 打包配置,支持手动分块。
路径别名 (resolve.alias
)
通过 alias
配置路径别名,简化模块导入。
CSS 配置 (css
)
preprocessorOptions
:配置 CSS 预处理器(如 SCSS、Less)。modules
:启用 CSS Modules。
环境变量 (env
)
envPrefix
:指定环境变量前缀(默认为VITE_
)。define
:定义全局变量。
依赖优化 (optimizeDeps
)
include
:预构建依赖。exclude
:排除依赖。
5. 环境变量
Vite 使用 .env
文件管理环境变量:
.env
:默认环境变量。.env.development
:开发环境变量。.env.production
:生产环境变量。
示例 .env
文件:
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=My Vite App
在代码中访问:
console.log(import.meta.env.VITE_API_BASE_URL);
6. TypeScript 支持
Vite 默认支持 TypeScript。只需安装 TypeScript 并创建 tsconfig.json
文件:
npm install typescript --save-dev
示例 tsconfig.json
:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": ["src"]
}
7. 部署
构建项目:
npm run build
构建结果会输出到 dist
目录,可直接部署到服务器。
8. 示例代码
以下是一个完整的 vite.config.js
示例:
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { fileURLToPath, URL } from 'node:url';
import legacy from '@vitejs/plugin-legacy';
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
plugins: [
vue(),
legacy({
targets: ['defaults', 'not IE 11'],
}),
visualizer({
open: true,
filename: 'bundle-analysis.html',
}),
],
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: env.VITE_API_BASE_URL || 'http://localhost:5000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: true,
minify: 'terser',
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'vue-router', 'axios'],
},
},
},
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`,
},
},
},
envPrefix: 'VITE_',
};
});
总结
通过以上详细配置,您可以充分利用 Vite 的强大功能,优化开发体验和项目性能。根据项目需求灵活调整配置,可以显著提升开发效率和构建质量。