配置文件(vite.config.js)结构解析
Vite.js 的配置文件 vite.config.js
是项目构建的核心,通过它可以定制化开发服务器、打包行为、插件集成等。理解其结构和常用配置项能显著提升开发效率。
配置文件基本结构
vite.config.js
默认导出一个对象,最简配置如下:
export default {
// 配置项
}
完整配置结构通常包含这些顶层字段:
export default defineConfig({
root: process.cwd(),
base: '/',
mode: 'development',
publicDir: 'public',
cacheDir: 'node_modules/.vite',
resolve: { /* 模块解析配置 */ },
css: { /* CSS 相关配置 */ },
json: { /* JSON 处理配置 */ },
esbuild: { /* ESBuild 配置 */ },
server: { /* 开发服务器配置 */ },
preview: { /* 预览服务器配置 */ },
build: { /* 生产构建配置 */ },
plugins: [ /* 插件列表 */ ],
optimizeDeps: { /* 依赖优化配置 */ },
worker: { /* Worker 配置 */ },
logLevel: 'info',
clearScreen: true
})
核心配置项详解
开发服务器配置 (server)
控制本地开发服务器的行为:
server: {
host: '0.0.0.0', // 监听所有网络接口
port: 3000, // 指定端口
open: true, // 自动打开浏览器
cors: true, // 启用 CORS
proxy: { // 代理配置
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
},
fs: { // 文件系统限制
strict: true,
allow: ['..'] // 允许访问上级目录
}
}
构建配置 (build)
控制生产环境打包行为:
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
assetsInlineLimit: 4096, // 小于 4KB 的资源内联
cssCodeSplit: true, // CSS 代码分割
sourcemap: false, // 是否生成 sourcemap
rollupOptions: { // Rollup 配置
input: {
main: 'index.html',
admin: 'admin.html'
},
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor'
}
}
}
},
minify: 'terser', // 代码压缩工具
terserOptions: { // Terser 配置
compress: {
drop_console: true
}
}
}
路径解析配置 (resolve)
控制模块路径解析规则:
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'components': path.resolve(__dirname, './src/components')
},
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
mainFields: ['module', 'jsnext:main', 'jsnext'],
dedupe: ['vue'] // 避免重复打包
}
CSS 相关配置
css: {
modules: {
localsConvention: 'camelCaseOnly', // 类名转换规则
generateScopedName: '[name]__[local]___[hash:base64:5]'
},
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
},
less: {
math: 'always',
globalVars: {
primary: '#1890ff'
}
}
},
postcss: {
plugins: [
require('autoprefixer'),
require('postcss-pxtorem')({
rootValue: 16,
propList: ['*']
})
]
}
}
插件系统配置
Vite 通过插件扩展功能:
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
plugins: [
vue(),
legacy({
targets: ['defaults', 'not IE 11']
}),
{
// 自定义插件
name: 'custom-plugin',
transform(code, id) {
if (/\.vue$/.test(id)) {
return code.replace(/process\.env\.NODE_ENV/g, JSON.stringify('production'))
}
}
}
]
环境变量与模式
支持多环境配置:
// vite.config.js
export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
define: {
__APP_VERSION__: JSON.stringify(env.VITE_APP_VERSION)
}
}
})
对应 .env
文件:
# .env.development
VITE_API_BASE=http://localhost:3000
VITE_APP_VERSION=1.0.0-dev
高级配置技巧
条件配置
根据命令动态配置:
export default defineConfig(({ command }) => {
const isBuild = command === 'build'
return {
base: isBuild ? '/production/' : '/',
plugins: [
isBuild ? mockPlugin() : null
].filter(Boolean)
}
})
配置合并
合并多个配置:
import { mergeConfig } from 'vite'
const baseConfig = {
server: { port: 3000 }
}
const devConfig = {
server: { open: true }
}
export default mergeConfig(baseConfig, devConfig)
自定义中间件
扩展开发服务器:
server: {
middlewareMode: true,
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url === '/custom') {
res.end('Hello from custom middleware')
} else {
next()
}
})
}
}
性能优化配置
依赖预构建
optimizeDeps: {
include: ['lodash-es', 'axios'],
exclude: ['vue-demi'],
entries: [
'src/main.js',
'src/entries/*.js'
],
esbuildOptions: {
target: 'es2020',
supported: {
bigint: true
}
}
}
Worker 配置
worker: {
format: 'es',
plugins: [vue()],
rollupOptions: {
output: {
assetFileNames: 'worker-assets/[name].[hash].[ext]'
}
}
}
调试配置
启用详细日志:
export default defineConfig({
logLevel: 'debug',
clearScreen: false,
server: {
middlewareMode: true,
watch: {
usePolling: true,
interval: 100
}
}
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:项目初始化与模板选择
下一篇:环境变量与模式管理