CodeL
以前端为翼,以 AI 为脑,向全栈而行
2026-03-31

Vite 配置管理完整教程

Vite 配置管理完整教程 从零到精通,覆盖开发服务器、构建配置、环境变量、插件管理等核心场景。 目录 一、核心概念 二、基础使用 三、进阶用法 四、实战场景 五、常见问题 六、总结速记 一、核心概念 1.1 什么是 V...

Vite 配置管理完整教程 #

从零到精通,覆盖开发服务器、构建配置、环境变量、插件管理等核心场景。


目录 #


一、核心概念 #

1.1 什么是 Vite? #

Vite(法语"快速",发音 /viːt/)是新一代前端构建工具。

大白话理解

Vite 就像一个"超级快"的开发助手:

  • 开发时:直接用浏览器加载源文件,秒级启动(不像 Webpack 要打包所有文件才能启动)
  • 生产时:用 Rolldown 高效打包,输出优化后的文件

核心优势

优势 说明 对比 Webpack
秒级启动 不打包,直接加载源文件 Webpack 启动要打包,慢
热更新快 只更新改动的模块,毫秒级 Webpack 要重新打包改动部分
配置简单 默认配置就能用,开箱即用 Webpack 配置复杂
原生 ESM 直接用浏览器 ES Modules Webpack 要编译成 bundle

1.2 Vite 配置文件在哪里? #

默认在项目根目录,文件名 vite.config.js(也支持 .ts):

my-project/
├── vite.config.js    ← 配置文件(默认位置)
├── package.json
├── src/
└── public/

1.3 配置文件基本结构 #

// vite.config.js - 最简单的配置
export default {
  // 配置项写在这里
}

推荐写法(带类型提示):

// 使用 defineConfig 获得 IDE 智能提示
import { defineConfig } from 'vite'
 
export default defineConfig({
  // 配置项写在这里,IDE 会提示可用选项
})

1.4 核心配置分类 #

类别 配置项 作用
开发服务器 server 端口、代理、HMR
构建输出 build 输出目录、打包格式
路径别名 resolve.alias @/componentssrc/components
环境变量 envDirenvPrefix .env 文件位置和前缀
插件 plugins 扩展功能(React、Vue 等)

二、基础使用 #

2.1 创建项目 + 默认配置 #

# 创建项目(自动生成 vite.config.js)
npm create vite@latest my-app
 
# 选择模板(比如 React + TypeScript)
# 按提示选择:React → TypeScript
 
cd my-app
npm install
npm run dev  # 启动开发服务器

生成的默认配置:

// vite.config.js(默认)
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
 
export default defineConfig({
  plugins: [react()],
})

2.2 配置开发服务器 #

最常用的配置:改端口 + 开启代理

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
 
export default defineConfig({
  plugins: [react()],
  
  // 开发服务器配置
  server: {
    port: 3000,           // 改端口(默认 5173)
    open: true,           // 自动打开浏览器
    host: '0.0.0.0',      // 允许局域网访问(手机也能看)
    
    // API 代理(解决跨域)
    proxy: {
      '/api': {
        target: 'http://localhost:8080',  // 后端地址
        changeOrigin: true,               // 修改请求头 Origin
        rewrite: (path) => path.replace(/^\/api/, '')  // 重写路径
      }
    }
  }
})

2.3 配置路径别名 #

告别 ../../../components/Button,用 @/components/Button

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'  // Node.js 内置模块
 
export default defineConfig({
  plugins: [react()],
  
  // 路径别名
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),    // @ → src 目录
      '@components': path.resolve(__dirname, 'src/components'),
      '@utils': path.resolve(__dirname, 'src/utils'),
    }
  }
})

使用示例

// 原来
import Button from '../../../components/Button'
import { formatDate } from '../../utils/date'
 
// 现在
import Button from '@/components/Button'
import { formatDate } from '@/utils/date'

注意:TypeScript 项目需要额外配置 tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"]
    }
  }
}

2.4 配置构建输出 #

import { defineConfig } from 'vite'
 
export default defineConfig({
  // 构建配置
  build: {
    outDir: 'dist',           // 输出目录(默认 dist)
    assetsDir: 'assets',      // 静态资源目录(默认 assets)
    sourcemap: true,          // 生成 sourcemap(方便调试)
    minify: 'esbuild',        // 压缩方式(默认 esbuild,最快)
    
    // 分包策略(避免单个文件太大)
    rollupOptions: {
      output: {
        manualChunks: {
          // 第三方库单独打包
          'vendor': ['react', 'react-dom'],
          'utils': ['lodash', 'axios']
        }
      }
    }
  }
})

三、进阶用法 #

3.1 环境变量配置 #

Vite 内置 .env 文件支持:

# .env(所有环境生效)
VITE_APP_TITLE=My App
VITE_API_BASE_URL=/api
 
# .env.development(开发环境)
VITE_API_BASE_URL=http://localhost:8080/api
 
# .env.production(生产环境)
VITE_API_BASE_URL=https://api.example.com

使用环境变量

// 代码中使用(必须是 VITE_ 开头)
console.log(import.meta.env.VITE_APP_TITLE)
console.log(import.meta.env.VITE_API_BASE_URL)

配置 envDir 和 envPrefix

import { defineConfig } from 'vite'
 
export default defineConfig({
  // 环境变量配置
  envDir: './env',           // .env 文件目录(默认项目根目录)
  envPrefix: 'VITE_',        // 环境变量前缀(默认 VITE_)
})

注意

  • 只有 VITE_ 开头的变量才能在代码中访问
  • 其他变量(如 API_KEY)只能在配置文件中通过 process.env 访问

3.2 条件配置(开发/生产区分) #

根据环境加载不同配置:

import { defineConfig } from 'vite'
 
export default defineConfig(({ command, mode }) => {
  // command: 'serve'(开发)或 'build'(构建)
  // mode: 'development' 或 'production'
  
  if (command === 'serve') {
    // 开发环境配置
    return {
      server: {
        port: 3000,
        proxy: {
          '/api': 'http://localhost:8080'
        }
      }
    }
  } else {
    // 生产构建配置
    return {
      build: {
        sourcemap: false,  // 生产不生成 sourcemap
        minify: 'esbuild'
      }
    }
  }
})

3.3 多环境配置文件 #

项目复杂时,拆分配置文件:

// vite.config.js(主配置)
import { defineConfig, loadEnv } from 'vite'
import viteBase from './vite.base'
import viteDev from './vite.dev'
import viteProd from './vite.prod'
 
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd())
  
  const config = command === 'serve' 
    ? viteDev(env) 
    : viteProd(env)
  
  return { ...viteBase, ...config }
})
 
// vite.base.js(公共配置)
export default {
  plugins: [],
  resolve: {
    alias: { '@': '/src' }
  }
}
 
// vite.dev.js(开发配置)
export default (env) => ({
  server: {
    port: 3000,
    proxy: {
      '/api': env.VITE_API_URL
    }
  }
})
 
// vite.prod.js(生产配置)
export default {
  build: {
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom']
        }
      }
    }
  }
}

3.4 插件配置 #

常用插件:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'         // React 支持
import vue from '@vitejs/plugin-vue'             // Vue 支持
import svgr from 'vite-plugin-svgr'              // SVG 转 React 组件
import compression from 'vite-plugin-compression' // Gzip 压缩
 
export default defineConfig({
  plugins: [
    react(),
    vue(),
    svgr(),                    // SVG 转 React 组件:<Icon />
    compression({              // 生产构建自动 Gzip
      algorithm: 'gzip',
      threshold: 10240         // 大于 10KB 才压缩
    })
  ]
})

四、实战场景 #

场景 1:前后端分离项目(API 代理) #

需求:前端 3000 端口,后端 8080 端口,前端 /api 请求转发到后端。

完整配置

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
 
export default defineConfig({
  plugins: [react()],
  
  server: {
    port: 3000,
    proxy: {
      // 所有 /api 请求转发到后端
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/api')  // 保持 /api 前缀
      },
      
      // WebSocket 代理
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true
      }
    }
  }
})

前端调用示例

// 直接请求 /api,Vite 自动转发
fetch('/api/users')
  .then(res => res.json())
  .then(data => console.log(data))

场景 2:多页面应用配置 #

需求:一个项目多个入口(比如 admin.html 和 index.html)。

完整配置

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
 
export default defineConfig({
  plugins: [react()],
  
  // 多页面入口
  build: {
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html'),
        admin: path.resolve(__dirname, 'admin.html'),
        login: path.resolve(__dirname, 'login.html')
      }
    }
  },
  
  // 路径别名
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
})

文件结构

my-project/
├── index.html        ← 主页入口
├── admin.html        ← 管理页入口
├── login.html        ← 登录页入口
├── src/
│   ├── main.js
│   ├── admin.js
│   ├── login.js
│   └── components/
└── vite.config.js

场景 3:CDN 部署 + 静态资源路径 #

需求:生产环境静态资源上传 CDN,/assets 改为 https://cdn.example.com/assets

完整配置

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
 
export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production'
  
  return {
    plugins: [react()],
    
    build: {
      // 生产环境使用 CDN 基础路径
      base: isProduction ? 'https://cdn.example.com/' : '/',
      
      assetsDir: 'assets',
      
      rollupOptions: {
        output: {
          // 文件名带 hash(CDN 缓存友好)
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      }
    }
  }
})

场景 4:构建性能优化 #

需求:大型项目构建太慢,需要分包 + 按需加载。

完整配置

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import compression from 'vite-plugin-compression'
 
export default defineConfig({
  plugins: [
    react(),
    compression({ algorithm: 'gzip' })  // Gzip 压缩
  ],
  
  build: {
    // 分包策略
    rollupOptions: {
      output: {
        manualChunks: (id) => {
          // node_modules 单独打包
          if (id.includes('node_modules')) {
            // React 相关
            if (id.includes('react') || id.includes('react-dom')) {
              return 'react-vendor'
            }
            // 工具库
            if (id.includes('lodash') || id.includes('axios')) {
              return 'utils-vendor'
            }
            // 其他第三方
            return 'vendor'
          }
        }
      }
    },
    
    // chunk 大小警告阈值
    chunkSizeWarningLimit: 500,  // 500KB 以上警告
    
    // CSS 代码分割
    cssCodeSplit: true
  }
})

场景 5:SSR 项目配置 #

需求:Next.js/Remix 风格的 SSR 项目配置。

完整配置

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
 
export default defineConfig({
  plugins: [react()],
  
  // SSR 构建配置
  build: {
    ssr: true,              // SSR 构建
    outDir: 'dist/server',  // SSR 输出目录
    rollupOptions: {
      input: 'src/entry-server.tsx'  // SSR 入口
    }
  },
  
  // 开发服务器 SSR 配置
  server: {
    middlewareMode: true    // 中间件模式(配合 Express/Koa)
  },
  
  // 客户端构建配置(单独配置)
  // npm run build -- --ssrManifest
})

五、常见问题 #

Q1:路径别名 TypeScript 报错? #

原因:Vite 和 TypeScript 配置不一致。

解决

// tsconfig.json 添加 paths 配置
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

Q2:开发环境跨域报错? #

原因:前端和后端端口不同,浏览器阻止跨域请求。

解决:配置 proxy:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      }
    }
  }
})

Q3:构建后静态资源 404? #

原因base 配置不对,资源路径与实际部署路径不一致。

解决

// vite.config.js
export default defineConfig({
  base: '/my-app/',  // 如果部署在 https://example.com/my-app/
})

Q4:环境变量 undefined? #

原因:变量名不以 VITE_ 开头。

解决

# .env 文件变量必须以 VITE_ 开头
VITE_API_KEY=xxx 能访问
API_KEY=xxx 不能访问(安全考虑)

Q5:构建产物太大? #

原因:没有分包,所有代码打包成一个文件。

解决:配置 manualChunks

build: {
  rollupOptions: {
    output: {
      manualChunks: {
        vendor: ['react', 'react-dom', 'lodash']
      }
    }
  }
}

六、总结速记 #

类型 核心要点
配置文件 vite.config.js + defineConfig()
开发服务器 server.portserver.proxyserver.open
路径别名 resolve.alias + tsconfig.json paths
构建输出 build.outDirbuild.sourcemapbuild.rollupOptions
环境变量 .env + VITE_ 前缀 + import.meta.env
分包优化 manualChunks 按库拆分

附录 #

A. 常用配置速查 #

// vite.config.js 常用配置模板
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
 
export default defineConfig(({ command, mode }) => ({
  plugins: [react()],
  
  resolve: {
    alias: { '@': path.resolve(__dirname, 'src') }
  },
  
  server: {
    port: 3000,
    open: true,
    proxy: { '/api': 'http://localhost:8080' }
  },
  
  build: {
    outDir: 'dist',
    sourcemap: mode !== 'production',
    rollupOptions: {
      output: {
        manualChunks: { vendor: ['react', 'react-dom'] }
      }
    }
  }
}))

B. CLI 命令速查 #

命令 说明
vite 启动开发服务器
vite build 生产构建
vite preview 预览构建产物
vite --port 4000 指定端口
vite --host 允许局域网访问

C. 推荐资源 #

名称 链接 说明
Vite 官方文档 https://vite.dev ✅ 官方
Vite GitHub https://github.com/vitejs/vite ✅ 源码
Awesome Vite https://github.com/vitejs/awesome-vite ✅ 插件收集
Vite 配置详解 https://vite.dev/config/ ✅ 配置文档

最后更新:2026-03-28