Skip to content

Vite 规范

核心原则

必须使用 Vite 作为项目构建工具,遵循本文档的配置规范,确保开发体验和构建产物的一致性。

项目初始化

创建新项目

bash
# 使用 Vite 创建 React + TypeScript 项目
npm create vite@latest my-app -- --template react-ts

# 进入项目目录
cd my-app

# 安装依赖
npm install

项目结构

my-app/
├── public/              # 静态资源(不经过构建)
├── src/
│   ├── assets/          # 需要构建的静态资源
│   ├── components/      # 组件目录
│   │   └── ui/          # shadcn/ui 组件
│   ├── hooks/           # 自定义 Hooks
│   ├── lib/             # 工具函数
│   │   └── utils.ts     # cn() 等工具函数
│   ├── pages/           # 页面组件
│   ├── services/        # API 服务
│   ├── stores/          # Zustand stores
│   ├── types/           # TypeScript 类型定义
│   ├── App.tsx          # 根组件
│   ├── main.tsx         # 入口文件
│   └── index.css        # 全局样式(Tailwind)
├── index.html           # HTML 模板
├── vite.config.ts       # Vite 配置
├── tsconfig.json        # TypeScript 配置
├── tailwind.config.ts   # Tailwind 配置(可选)
├── components.json      # shadcn/ui 配置
└── package.json

Vite 配置

基础配置

typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
});

完整配置示例

typescript
// 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'),
      },
    },

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

    build: {
      outDir: 'dist',
      sourcemap: mode !== 'production',
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['react', 'react-dom', 'react-router'],
            ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
          },
        },
      },
    },

    // 测试配置(Vitest)
    test: {
      globals: true,
      environment: 'jsdom',
      setupFiles: './src/test/setup.ts',
      css: true,
    },
  };
});

路径别名

配置约束

  • 必须配置 @/* 路径别名指向 src/*
  • 必须同步更新 tsconfig.json 中的 paths 配置

tsconfig.json 配置

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

使用示例

typescript
// ✅ 正确 - 使用路径别名
import { Button } from '@/components/ui/button';
import { useUserStore } from '@/stores/user';
import { cn } from '@/lib/utils';

// ❌ 错误 - 使用相对路径(层级过深时)
import { Button } from '../../../components/ui/button';

环境变量

配置约束

  • 必须使用 VITE_ 前缀定义客户端环境变量
  • 禁止在代码中硬编码 API 地址或密钥
  • 应该为不同环境创建独立的 .env 文件

环境变量文件

bash
# .env - 所有环境共享
VITE_APP_TITLE=My App

# .env.development - 开发环境
VITE_API_BASE_URL=http://localhost:8080

# .env.production - 生产环境
VITE_API_BASE_URL=https://api.example.com

类型声明

typescript
// src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_APP_TITLE: string;
  readonly VITE_API_BASE_URL: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

使用示例

typescript
// ✅ 正确 - 使用环境变量
const apiUrl = import.meta.env.VITE_API_BASE_URL;
const appTitle = import.meta.env.VITE_APP_TITLE;

// ❌ 错误 - 硬编码
const apiUrl = 'http://localhost:8080';

插件使用

常用插件

插件用途
@vitejs/plugin-reactReact 支持(JSX、Fast Refresh)
vite-plugin-compressionGzip/Brotli 压缩
vite-plugin-pwaPWA 支持
vite-plugin-svgrSVG 作为 React 组件

插件配置示例

typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import compression from 'vite-plugin-compression';
import svgr from 'vite-plugin-svgr';

export default defineConfig({
  plugins: [
    react(),
    svgr(),
    compression({
      algorithm: 'gzip',
      ext: '.gz',
    }),
  ],
});

开发服务器

配置约束

  • 应该配置代理避免跨域问题
  • 应该启用自动打开浏览器
  • 禁止将开发服务器暴露到公网

代理配置

typescript
// vite.config.ts
export default defineConfig({
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
});

构建优化

代码分割

typescript
// vite.config.ts
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          // 将 React 相关库打包到单独的 chunk
          vendor: ['react', 'react-dom'],
          // 将路由相关库打包到单独的 chunk
          router: ['react-router'],
          // 将 UI 组件库打包到单独的 chunk
          ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
        },
      },
    },
  },
});

构建产物分析

bash
# 安装分析插件
npm install -D rollup-plugin-visualizer

# 配置插件
typescript
// vite.config.ts
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  plugins: [
    react(),
    visualizer({
      open: true,
      filename: 'stats.html',
    }),
  ],
});

禁止的做法

  • 禁止在 vite.config.ts 中硬编码敏感信息
  • 禁止使用 webpack 或其他构建工具
  • 禁止省略路径别名配置
  • 禁止.env.local 文件提交到版本控制
  • 禁止在生产环境启用 sourcemap(除非调试需要)