乐闻世界logo
搜索文章和话题

Vite 的配置文件有哪些常用选项?如何配置路径别名?

2月19日 19:14

Vite 提供了多种配置方式来满足不同项目的需求。以下是 Vite 配置的详细说明:

配置文件

Vite 会自动从以下位置加载配置文件(按优先级排序):

  1. vite.config.js
  2. vite.config.mjs
  3. vite.config.ts
  4. vite.config.cjs

基本配置结构

javascript
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { port: 3000, open: true }, build: { outDir: 'dist', sourcemap: true } })

常用配置选项

开发服务器配置(server)

  • port:指定开发服务器端口
  • host:指定服务器主机名
  • open:启动时自动打开浏览器
  • proxy:配置代理,解决跨域问题
  • cors:配置 CORS 策略
  • https:启用 HTTPS

构建配置(build)

  • outDir:输出目录
  • assetsDir:静态资源目录
  • sourcemap:是否生成 source map
  • minify:压缩方式(terser、esbuild)
  • target:构建目标浏览器
  • rollupOptions:Rollup 配置选项
  • chunkSizeWarningLimit:chunk 大小警告阈值

路径别名(resolve.alias)

javascript
resolve: { alias: { '@': '/src', '@components': '/src/components' } }

CSS 配置(css)

  • preprocessorOptions:预处理器选项
  • modules:CSS Modules 配置
  • postcss:PostCSS 配置

依赖优化配置(optimizeDeps)

  • include:强制包含的依赖
  • exclude:排除的依赖
  • esbuildOptions:esbuild 选项

环境变量

Vite 支持通过 .env 文件配置环境变量:

  • .env:所有环境
  • .env.development:开发环境
  • .env.production:生产环境
  • .env.local:本地覆盖

环境变量必须以 VITE_ 开头才能在客户端代码中访问。

条件配置

javascript
export default defineConfig(({ command, mode }) => { if (command === 'serve') { return { /* dev config */ } } else { return { /* build config */ } } })

TypeScript 支持

使用 defineConfig 可以获得完整的类型提示和智能补全。

标签:Vite