react-vite-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React + Vite Best Practices

React + Vite 最佳实践

Comprehensive performance optimization guide for React applications built with Vite. Contains 40+ rules across 8 categories, prioritized by impact to guide code generation and refactoring.
基于Vite构建的React应用性能优化综合指南。包含8个分类下的40+条规则,按影响优先级排序,用于指导代码生成与重构。

When to Apply

适用场景

Reference these guidelines when:
  • Configuring Vite for React projects
  • Implementing code splitting and lazy loading
  • Optimizing build output and bundle size
  • Setting up development environment
  • Reviewing code for performance issues
在以下场景中参考本指南:
  • 为React项目配置Vite
  • 实现代码分割与懒加载
  • 优化构建输出与包体积
  • 搭建开发环境
  • 审查代码中的性能问题

Rule Categories by Priority

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Build OptimizationCRITICAL
build-
2Code SplittingCRITICAL
split-
3Development PerformanceHIGH
dev-
4Asset HandlingHIGH
asset-
5Environment ConfigMEDIUM
env-
6HMR OptimizationMEDIUM
hmr-
7Bundle AnalysisLOW-MEDIUM
bundle-
8Advanced PatternsLOW
advanced-
优先级分类影响程度前缀
1构建优化关键
build-
2代码分割关键
split-
3开发性能
dev-
4资源处理
asset-
5环境配置
env-
6HMR优化
hmr-
7包分析低-中
bundle-
8高级模式
advanced-

Quick Reference

快速参考

1. Build Optimization (CRITICAL)

1. 构建优化(关键)

  • build-manual-chunks
    - Configure manual chunks for vendor separation
  • build-minify-terser
    - Use Terser for production minification
  • build-target-modern
    - Target modern browsers for smaller bundles
  • build-sourcemap-production
    - Configure sourcemaps appropriately
  • build-output-structure
    - Organize output directory structure
  • build-chunk-size-limit
    - Set appropriate chunk size warnings
  • build-manual-chunks
    - 配置手动chunk以分离第三方依赖
  • build-minify-terser
    - 使用Terser进行生产环境代码压缩
  • build-target-modern
    - 针对现代浏览器编译以减小包体积
  • build-sourcemap-production
    - 合理配置生产环境sourcemap
  • build-output-structure
    - 整理输出目录结构
  • build-chunk-size-limit
    - 设置合理的chunk大小警告阈值

2. Code Splitting (CRITICAL)

2. 代码分割(关键)

  • split-route-lazy
    - Use React.lazy() for route-based splitting
  • split-suspense-boundaries
    - Wrap lazy components with Suspense
  • split-dynamic-imports
    - Use dynamic imports for heavy components
  • split-preload-critical
    - Preload critical chunks on interaction
  • split-named-chunks
    - Use named chunks for better caching
  • split-vendor-separation
    - Separate vendor from application code
  • split-route-lazy
    - 使用React.lazy()实现基于路由的代码分割
  • split-suspense-boundaries
    - 用Suspense包裹懒加载组件
  • split-dynamic-imports
    - 对大型组件使用动态导入
  • split-preload-critical
    - 在交互时预加载关键chunk
  • split-named-chunks
    - 使用命名chunk提升缓存效率
  • split-vendor-separation
    - 将第三方依赖与业务代码分离

3. Development Performance (HIGH)

3. 开发性能(高)

  • dev-dependency-prebundling
    - Configure dependency pre-bundling
  • dev-exclude-large-deps
    - Exclude large deps from optimization
  • dev-warmup-frequent
    - Warmup frequently used modules
  • dev-server-config
    - Optimize dev server configuration
  • dev-hmr-overlay
    - Configure HMR error overlay
  • dev-dependency-prebundling
    - 配置依赖预构建
  • dev-exclude-large-deps
    - 将大型依赖排除在优化范围外
  • dev-warmup-frequent
    - 预加载常用模块
  • dev-server-config
    - 优化开发服务器配置
  • dev-hmr-overlay
    - 配置HMR错误覆盖层

4. Asset Handling (HIGH)

4. 资源处理(高)

  • asset-inline-limit
    - Set appropriate asset inline limit
  • asset-public-dir
    - Configure public directory correctly
  • asset-import-syntax
    - Use correct asset import syntax
  • asset-svg-components
    - Handle SVGs as React components
  • asset-image-optimization
    - Optimize image loading
  • asset-font-loading
    - Optimize font loading strategy
  • asset-inline-limit
    - 设置合理的资源内联阈值
  • asset-public-dir
    - 正确配置公共目录
  • asset-import-syntax
    - 使用正确的资源导入语法
  • asset-svg-components
    - 将SVG作为React组件处理
  • asset-image-optimization
    - 优化图片加载
  • asset-font-loading
    - 优化字体加载策略

5. Environment Configuration (MEDIUM)

5. 环境配置(中)

  • env-vite-prefix
    - Use VITE_ prefix for client variables
  • env-type-definitions
    - Type environment variables
  • env-mode-specific
    - Use mode-specific env files
  • env-sensitive-data
    - Never expose sensitive data
  • env-build-time
    - Understand build-time replacement
  • env-vite-prefix
    - 客户端环境变量使用VITE_前缀
  • env-type-definitions
    - 为环境变量添加类型定义
  • env-mode-specific
    - 使用对应模式的环境变量文件
  • env-sensitive-data
    - 绝不暴露敏感数据
  • env-build-time
    - 理解构建时代码替换逻辑

6. HMR Optimization (MEDIUM)

6. HMR优化(中)

  • hmr-fast-refresh
    - Ensure Fast Refresh works correctly
  • hmr-preserve-state
    - Preserve component state during HMR
  • hmr-boundary-setup
    - Set up proper HMR boundaries
  • hmr-custom-handlers
    - Implement custom HMR handlers
  • hmr-fast-refresh
    - 确保Fast Refresh正常工作
  • hmr-preserve-state
    - 在HMR过程中保留组件状态
  • hmr-boundary-setup
    - 设置合理的HMR边界
  • hmr-custom-handlers
    - 实现自定义HMR处理器

7. Bundle Analysis (LOW-MEDIUM)

7. 包分析(低-中)

  • bundle-visualizer
    - Use rollup-plugin-visualizer
  • bundle-analyze-deps
    - Analyze dependency sizes
  • bundle-tree-shaking
    - Ensure proper tree shaking
  • bundle-dead-code
    - Eliminate dead code
  • bundle-css-splitting
    - Configure CSS code splitting
  • bundle-visualizer
    - 使用rollup-plugin-visualizer
  • bundle-analyze-deps
    - 分析依赖包大小
  • bundle-tree-shaking
    - 确保Tree Shaking正常生效
  • bundle-dead-code
    - 消除无用代码
  • bundle-css-splitting
    - 配置CSS代码分割

8. Advanced Patterns (LOW)

8. 高级模式(低)

  • advanced-ssr-config
    - Configure for SSR if needed
  • advanced-library-mode
    - Build as library
  • advanced-multi-page
    - Multi-page application setup
  • advanced-worker-threads
    - Web Worker integration
  • advanced-wasm
    - WebAssembly integration
  • advanced-ssr-config
    - 按需配置SSR
  • advanced-library-mode
    - 以库模式构建
  • advanced-multi-page
    - 多页面应用配置
  • advanced-worker-threads
    - Web Worker集成
  • advanced-wasm
    - WebAssembly集成

Essential Configurations

核心配置示例

Recommended vite.config.ts

推荐的vite.config.ts

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

  build: {
    target: 'esnext',
    minify: 'terser',
    sourcemap: false,
    chunkSizeWarningLimit: 500,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
        },
      },
    },
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
  },

  optimizeDeps: {
    include: ['react', 'react-dom'],
  },

  server: {
    port: 3000,
    open: true,
    hmr: {
      overlay: true,
    },
  },
})
typescript
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'),
    },
  },

  build: {
    target: 'esnext',
    minify: 'terser',
    sourcemap: false,
    chunkSizeWarningLimit: 500,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
        },
      },
    },
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
  },

  optimizeDeps: {
    include: ['react', 'react-dom'],
  },

  server: {
    port: 3000,
    open: true,
    hmr: {
      overlay: true,
    },
  },
})

Route-Based Code Splitting

基于路由的代码分割

typescript
import { lazy, Suspense } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'

// Lazy load route components
const Home = lazy(() => import('./pages/Home'))
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Settings = lazy(() => import('./pages/Settings'))

// Named chunks for better debugging
const Profile = lazy(() =>
  import(/* webpackChunkName: "profile" */ './pages/Profile')
)

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<LoadingSpinner />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
          <Route path="/profile" element={<Profile />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  )
}
typescript
import { lazy, Suspense } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'

// 懒加载路由组件
const Home = lazy(() => import('./pages/Home'))
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Settings = lazy(() => import('./pages/Settings'))

// 命名chunk便于调试
const Profile = lazy(() =>
  import(/* webpackChunkName: "profile" */ './pages/Profile')
)

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<LoadingSpinner />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
          <Route path="/profile" element={<Profile />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  )
}

Environment Variables

环境变量配置

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

interface ImportMetaEnv {
  readonly VITE_API_URL: string
  readonly VITE_APP_TITLE: string
  readonly VITE_ENABLE_ANALYTICS: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
typescript
// Usage
const apiUrl = import.meta.env.VITE_API_URL
const isDev = import.meta.env.DEV
const isProd = import.meta.env.PROD
typescript
// src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string
  readonly VITE_APP_TITLE: string
  readonly VITE_ENABLE_ANALYTICS: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
typescript
// 使用示例
const apiUrl = import.meta.env.VITE_API_URL
const isDev = import.meta.env.DEV
const isProd = import.meta.env.PROD

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/build-manual-chunks.md
rules/split-route-lazy.md
rules/_sections.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
阅读单个规则文件获取详细说明与代码示例:
rules/build-manual-chunks.md
rules/split-route-lazy.md
rules/_sections.md
每个规则文件包含:
  • 规则重要性的简要说明
  • 错误代码示例及问题分析
  • 正确代码示例及解释
  • 额外背景信息与参考资料