Vite配置指南

完整vite.config.ts模板

import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {
    plugins: [
      react(),
    ],

    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@components': path.resolve(__dirname, './src/components'),
        '@hooks': path.resolve(__dirname, './src/hooks'),
      },
    },

    server: {
      port: 3000,
      proxy: {
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },

    build: {
      outDir: 'dist',
      sourcemap: mode === 'development',
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['react', 'react-dom'],
            router: ['react-router-dom'],
          },
        },
      },
      chunkSizeWarningLimit: 600,
    },

    define: {
      __APP_VERSION__: JSON.stringify(env.npm_package_version),
    },
  }
})

环境变量

# .env (all modes)
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My App

# .env.development
VITE_API_URL=http://localhost:8080

# .env.production
VITE_API_URL=https://api.prod.com

# Access in code (only VITE_ prefix exposed to client)
const apiUrl = import.meta.env.VITE_API_URL

常用Vite插件

插件用途
@vitejs/plugin-reactReact快速刷新
@vitejs/plugin-vueVue 3支持
vite-plugin-pwaPWA/Service Worker
unplugin-auto-importAPI自动导入
vite-bundle-visualizer包大小分析
@vitejs/plugin-legacy旧浏览器支持