react-vite-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact + 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
按优先级划分的规则分类
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Build Optimization | CRITICAL | |
| 2 | Code Splitting | CRITICAL | |
| 3 | Development Performance | HIGH | |
| 4 | Asset Handling | HIGH | |
| 5 | Environment Config | MEDIUM | |
| 6 | HMR Optimization | MEDIUM | |
| 7 | Bundle Analysis | LOW-MEDIUM | |
| 8 | Advanced Patterns | LOW | |
| 优先级 | 分类 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 构建优化 | 关键 | |
| 2 | 代码分割 | 关键 | |
| 3 | 开发性能 | 高 | |
| 4 | 资源处理 | 高 | |
| 5 | 环境配置 | 中 | |
| 6 | HMR优化 | 中 | |
| 7 | 包分析 | 低-中 | |
| 8 | 高级模式 | 低 | |
Quick Reference
快速参考
1. Build Optimization (CRITICAL)
1. 构建优化(关键)
- - Configure manual chunks for vendor separation
build-manual-chunks - - Use Terser for production minification
build-minify-terser - - Target modern browsers for smaller bundles
build-target-modern - - Configure sourcemaps appropriately
build-sourcemap-production - - Organize output directory structure
build-output-structure - - Set appropriate chunk size warnings
build-chunk-size-limit
- - 配置手动chunk以分离第三方依赖
build-manual-chunks - - 使用Terser进行生产环境代码压缩
build-minify-terser - - 针对现代浏览器编译以减小包体积
build-target-modern - - 合理配置生产环境sourcemap
build-sourcemap-production - - 整理输出目录结构
build-output-structure - - 设置合理的chunk大小警告阈值
build-chunk-size-limit
2. Code Splitting (CRITICAL)
2. 代码分割(关键)
- - Use React.lazy() for route-based splitting
split-route-lazy - - Wrap lazy components with Suspense
split-suspense-boundaries - - Use dynamic imports for heavy components
split-dynamic-imports - - Preload critical chunks on interaction
split-preload-critical - - Use named chunks for better caching
split-named-chunks - - Separate vendor from application code
split-vendor-separation
- - 使用React.lazy()实现基于路由的代码分割
split-route-lazy - - 用Suspense包裹懒加载组件
split-suspense-boundaries - - 对大型组件使用动态导入
split-dynamic-imports - - 在交互时预加载关键chunk
split-preload-critical - - 使用命名chunk提升缓存效率
split-named-chunks - - 将第三方依赖与业务代码分离
split-vendor-separation
3. Development Performance (HIGH)
3. 开发性能(高)
- - Configure dependency pre-bundling
dev-dependency-prebundling - - Exclude large deps from optimization
dev-exclude-large-deps - - Warmup frequently used modules
dev-warmup-frequent - - Optimize dev server configuration
dev-server-config - - Configure HMR error overlay
dev-hmr-overlay
- - 配置依赖预构建
dev-dependency-prebundling - - 将大型依赖排除在优化范围外
dev-exclude-large-deps - - 预加载常用模块
dev-warmup-frequent - - 优化开发服务器配置
dev-server-config - - 配置HMR错误覆盖层
dev-hmr-overlay
4. Asset Handling (HIGH)
4. 资源处理(高)
- - Set appropriate asset inline limit
asset-inline-limit - - Configure public directory correctly
asset-public-dir - - Use correct asset import syntax
asset-import-syntax - - Handle SVGs as React components
asset-svg-components - - Optimize image loading
asset-image-optimization - - Optimize font loading strategy
asset-font-loading
- - 设置合理的资源内联阈值
asset-inline-limit - - 正确配置公共目录
asset-public-dir - - 使用正确的资源导入语法
asset-import-syntax - - 将SVG作为React组件处理
asset-svg-components - - 优化图片加载
asset-image-optimization - - 优化字体加载策略
asset-font-loading
5. Environment Configuration (MEDIUM)
5. 环境配置(中)
- - Use VITE_ prefix for client variables
env-vite-prefix - - Type environment variables
env-type-definitions - - Use mode-specific env files
env-mode-specific - - Never expose sensitive data
env-sensitive-data - - Understand build-time replacement
env-build-time
- - 客户端环境变量使用VITE_前缀
env-vite-prefix - - 为环境变量添加类型定义
env-type-definitions - - 使用对应模式的环境变量文件
env-mode-specific - - 绝不暴露敏感数据
env-sensitive-data - - 理解构建时代码替换逻辑
env-build-time
6. HMR Optimization (MEDIUM)
6. HMR优化(中)
- - Ensure Fast Refresh works correctly
hmr-fast-refresh - - Preserve component state during HMR
hmr-preserve-state - - Set up proper HMR boundaries
hmr-boundary-setup - - Implement custom HMR handlers
hmr-custom-handlers
- - 确保Fast Refresh正常工作
hmr-fast-refresh - - 在HMR过程中保留组件状态
hmr-preserve-state - - 设置合理的HMR边界
hmr-boundary-setup - - 实现自定义HMR处理器
hmr-custom-handlers
7. Bundle Analysis (LOW-MEDIUM)
7. 包分析(低-中)
- - Use rollup-plugin-visualizer
bundle-visualizer - - Analyze dependency sizes
bundle-analyze-deps - - Ensure proper tree shaking
bundle-tree-shaking - - Eliminate dead code
bundle-dead-code - - Configure CSS code splitting
bundle-css-splitting
- - 使用rollup-plugin-visualizer
bundle-visualizer - - 分析依赖包大小
bundle-analyze-deps - - 确保Tree Shaking正常生效
bundle-tree-shaking - - 消除无用代码
bundle-dead-code - - 配置CSS代码分割
bundle-css-splitting
8. Advanced Patterns (LOW)
8. 高级模式(低)
- - Configure for SSR if needed
advanced-ssr-config - - Build as library
advanced-library-mode - - Multi-page application setup
advanced-multi-page - - Web Worker integration
advanced-worker-threads - - WebAssembly integration
advanced-wasm
- - 按需配置SSR
advanced-ssr-config - - 以库模式构建
advanced-library-mode - - 多页面应用配置
advanced-multi-page - - Web Worker集成
advanced-worker-threads - - WebAssembly集成
advanced-wasm
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.PRODtypescript
// 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.PRODHow to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/build-manual-chunks.md
rules/split-route-lazy.md
rules/_sections.mdEach 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每个规则文件包含:
- 规则重要性的简要说明
- 错误代码示例及问题分析
- 正确代码示例及解释
- 额外背景信息与参考资料