跳到主要内容

配置文件

配置文件基础

Vite 会自动解析项目根目录下的配置文件。支持的配置文件名:

  • vite.config.js
  • vite.config.mjs
  • vite.config.ts
  • vite.config.cjs

推荐使用 vite.config.jsvite.config.ts(TypeScript 项目)。

基本配置结构

import { defineConfig } from 'vite'

export default defineConfig({
// 配置选项
})

defineConfig 辅助函数提供类型提示,无需 JSDoc 注解即可获得 IDE 智能提示。

使用 JSDoc 类型提示

如果不使用 defineConfig,也可以用 JSDoc 注解:

/** @type {import('vite').UserConfig} */
export default {
// 配置选项
}

TypeScript 配置文件

对于 TypeScript 项目,可以使用 vite.config.ts

import { defineConfig } from 'vite'
import type { UserConfig } from 'vite'

export default defineConfig({
// 配置选项
} satisfies UserConfig)

条件配置

如果配置需要根据命令(serve 或 build)、模式或其他条件动态确定,可以导出一个函数:

import { defineConfig } from 'vite'

export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
if (command === 'serve') {
return {
// 开发环境特定配置
server: {
port: 3000,
},
}
} else {
// command === 'build'
return {
// 生产环境特定配置
build: {
rollupOptions: {
// 生产构建选项
},
},
}
}
})

参数说明

参数类型说明
command'build' | 'serve'当前运行的命令(serve 表示开发服务器,build 表示生产构建)
modestring应用运行的模式
isSsrBuildboolean | undefined是否为 SSR 构建
isPreviewboolean | undefined是否为预览模式

异步配置

如果配置需要调用异步函数,可以导出异步函数:

import { defineConfig } from 'vite'

export default defineConfig(async ({ command, mode }) => {
const data = await asyncFunction()
return {
// 使用异步获取的数据
define: {
__APP_DATA__: JSON.stringify(data),
},
}
})

常用配置选项

项目根目录

export default defineConfig({
// 项目根目录(index.html 所在位置)
// 默认:process.cwd()
root: process.cwd(),

// 基础公共路径
// 默认:'/'
base: '/',

// 资源公共路径(相对于 base)
// 默认:'./'
publicDir: 'public',
})

路径解析

import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
resolve: {
// 路径别名
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@assets': path.resolve(__dirname, './src/assets'),
},

// 导入时省略的扩展名
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
},
})

使用路径别名后,可以这样导入模块:

// 不使用别名
import Button from '../../../components/Button.vue'

// 使用别名
import Button from '@components/Button.vue'

开发服务器配置

export default defineConfig({
server: {
// 服务器端口
port: 3000,

// 自动打开浏览器
open: true,

// 允许外部访问
host: true, // 或指定 IP:'0.0.0.0'

// 启用 HTTPS
https: false, // 或传入 https 配置对象

// 热更新配置
hmr: {
overlay: true, // 显示编译错误遮罩
},

// 代理配置
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
'/ws': {
target: 'ws://localhost:8080',
ws: true,
},
},

// CORS 配置
cors: true,

// 自定义中间件
middlewareMode: false,
},
})

构建配置

export default defineConfig({
build: {
// 输出目录
outDir: 'dist',

// 静态资源目录
assetsDir: 'assets',

// 是否生成 source map
sourcemap: false,

// 是否清空输出目录
emptyOutDir: true,

// 目标浏览器版本
target: 'es2015',

// 是否压缩代码
minify: 'esbuild', // 'esbuild' | 'terser' | false

// CSS 代码分割
cssCodeSplit: true,

// 资源内联限制(小于此值的资源会被内联为 base64)
assetsInlineLimit: 4096, // 4KB

// 块大小警告阈值
chunkSizeWarningLimit: 500, // 500KB

// Rollup 选项
rollupOptions: {
// 入口文件
input: {
main: path.resolve(__dirname, 'index.html'),
},
// 输出配置
output: {
// 入口文件命名
entryFileNames: 'js/[name]-[hash].js',
// 块文件命名
chunkFileNames: 'js/[name]-[hash].js',
// 资源文件命名
assetFileNames: (assetInfo) => {
const info = assetInfo.name.split('.')
const ext = info[info.length - 1]
if (/\.(png|jpe?g|gif|svg|webp|ico)$/i.test(assetInfo.name)) {
return 'img/[name]-[hash][extname]'
}
if (/\.(woff2?|eot|ttf|otf)$/i.test(assetInfo.name)) {
return 'fonts/[name]-[hash][extname]'
}
return '[name]-[hash][extname]'
},
},
},
},
})

CSS 配置

export default defineConfig({
css: {
// CSS Modules 配置
modules: {
scopeBehaviour: 'local',
localsConvention: 'camelCaseOnly',
},

// 预处理器选项
preprocessorOptions: {
scss: {
additionalData: `@import "./src/styles/vars.scss";`,
},
less: {
math: 'parens-division',
},
stylus: {
imports: [path.resolve(__dirname, './src/styles/vars.styl')],
},
},

// PostCSS 配置(会自动加载 postcss.config.js)
postcss: {
// 内联配置或配置文件路径
},

// 开发环境是否生成 source map
devSourcemap: false,
},
})

esbuild 配置

Vite 使用 esbuild 进行 JavaScript/TypeScript 转换:

export default defineConfig({
esbuild: {
// JSX 配置
jsxFactory: 'h',
jsxFragment: 'Fragment',

// 自动注入 JSX 辅助函数
jsxInject: `import React from 'react'`,

// 目标环境
target: 'es2020',

// 是否保留 console 和 debugger
drop: ['console', 'debugger'],

// 定义全局常量
define: {
__VERSION__: '"1.0.0"',
},
},
})

依赖优化

export default defineConfig({
optimizeDeps: {
// 预构建的入口
entries: ['./src/main.js'],

// 强制预构建的依赖
include: [
'vue',
'vue-router',
'pinia',
],

// 排除不需要预构建的依赖
exclude: ['@zougt/some-lib'],

// esbuild 选项
esbuildOptions: {
target: 'es2020',
},
},
})

插件使用

Vite 插件扩展了构建流程的功能。插件可以是:

  • 官方插件
  • 社区插件
  • 自定义插件

安装官方插件

# Vue 插件
npm install -D @vitejs/plugin-vue

# React 插件
npm install -D @vitejs/plugin-react

# React SWC 插件(更快的编译)
npm install -D @vitejs/plugin-react-swc

# Legacy 插件(支持旧浏览器)
npm install -D @vitejs/plugin-legacy

配置插件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
plugins: [
// 使用插件
vue(),

// 插件可以配置选项
vue({
template: {
compilerOptions: {
// Vue 编译器选项
},
},
}),
],
})

条件使用插件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'

export default defineConfig(({ mode }) => ({
plugins: [
vue(),
// 只在生产环境使用 legacy 插件
mode === 'production' && legacy({
targets: ['defaults', 'not IE 11'],
}),
].filter(Boolean),
}))

完整配置示例

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig(({ command, mode }) => ({
// 基础配置
root: process.cwd(),
base: '/',
publicDir: 'public',

// 路径解析
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
'@components': resolve(__dirname, 'src/components'),
'@views': resolve(__dirname, 'src/views'),
'@utils': resolve(__dirname, 'src/utils'),
'@assets': resolve(__dirname, 'src/assets'),
},
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
},

// 插件
plugins: [
vue(),
],

// 开发服务器
server: {
port: 3000,
open: true,
host: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},

// 构建配置
build: {
outDir: 'dist',
sourcemap: mode === 'development',
rollupOptions: {
output: {
manualChunks: {
// 代码分割
vendor: ['vue', 'vue-router', 'pinia'],
},
},
},
},

// CSS 配置
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/vars.scss" as *;`,
},
},
},

// 依赖优化
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia'],
},
}))

在配置中使用环境变量

加载 .env 文件

Vite deliberately 延迟加载 .env 文件直到用户配置解析完成后,因为加载的文件集取决于 rootenvDir 等配置选项。

如果需要在配置中使用环境变量,可以手动加载:

import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
// 加载当前模式下的环境变量
const env = loadEnv(mode, process.cwd(), '')

return {
// 使用环境变量
server: {
port: env.VITE_PORT ? Number(env.VITE_PORT) : 3000,
},
define: {
__API_URL__: JSON.stringify(env.VITE_API_URL),
},
}
})

loadEnv 参数说明

loadEnv(mode, envDir, prefixes)
参数说明
mode应用运行的模式
envDir环境文件所在的目录
prefixes环境变量前缀,默认为 "VITE_"。设置为空字符串 "" 加载所有变量

配置文件位置

可以通过 --config CLI 选项指定配置文件:

vite --config my-config.js

配置文件路径相对于当前工作目录解析。

小结

本章我们深入学习了 Vite 的配置文件:

  1. 基础配置:使用 defineConfig 获得类型提示
  2. 条件配置:根据命令、模式动态返回配置
  3. 常用选项
    • resolve.alias:路径别名
    • server:开发服务器配置
    • build:生产构建配置
    • css:CSS 处理配置
  4. 插件使用:安装和配置 Vite 插件
  5. 环境变量:在配置中加载和使用 .env 变量

配置文件是定制 Vite 行为的核心,掌握这些配置选项将帮助你构建更高效、更符合项目需求的开发环境。