react-vite-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact + Vite Expert
React + Vite 专家指南
Overview
概述
Transform into a React + Vite expert with deep knowledge of modern React development patterns, optimal project organization, performance optimization techniques, and production-ready configurations. This skill provides everything needed to build fast, maintainable, and scalable React applications using Vite as the build tool.
深入掌握现代React开发模式、最优项目组织方式、性能优化技巧以及生产就绪配置,成为React + Vite专家。本技能提供使用Vite作为构建工具,构建快速、可维护且可扩展的React应用所需的全部内容。
Core Capabilities
核心功能
1. Project Architecture & Organization
1. 项目架构与组织
Guide users in structuring React applications for maximum maintainability and scalability.
Reference:
references/project_architecture.mdThis comprehensive guide covers:
- Folder structure patterns: Feature-based, atomic design, domain-driven
- File organization: Colocation strategies, naming conventions
- Import strategies: Path aliases, barrel exports, tree-shaking
- State management organization: Local vs global, where to put state
- Scaling guidelines: How to evolve structure as app grows
When to consult:
- User asks "how should I organize my React project?"
- Starting a new project
- Refactoring existing project structure
- App is becoming hard to navigate
- Need to establish team conventions
Key Decision Trees:
- Feature-based vs Component-based: Read section "Optimal Folder Structure"
- State management strategy: Read section "State Management Strategies"
- Import organization: Read section "Import Strategies"
指导用户构建具有高可维护性和可扩展性的React应用结构。
参考文档:
references/project_architecture.md本全面指南涵盖:
- 文件夹结构模式:基于功能、原子设计、领域驱动
- 文件组织:就近放置策略、命名规范
- 导入策略:路径别名、桶式导出、摇树优化
- 状态管理组织:局部vs全局状态、状态存放位置
- 扩展指南:应用成长时如何演进结构
适用场景:
- 用户询问“我该如何组织我的React项目?”
- 启动新项目
- 重构现有项目结构
- 应用变得难以导航
- 需要建立团队规范
关键决策树:
- 基于功能vs基于组件:阅读“最优文件夹结构”章节
- 状态管理策略:阅读“状态管理策略”章节
- 导入组织:阅读“导入策略”章节
2. Code Generation & Scaffolding
2. 代码生成与脚手架
Automate component, hook, and feature creation with production-ready templates.
Scripts available:
scripts/create_component.py- Component file (.tsx)
- TypeScript types (.types.ts)
- CSS Module (.module.css)
- Tests (.test.tsx)
- Storybook story (.stories.tsx) [optional]
- Index file for clean imports
bash
undefined使用生产就绪模板自动生成组件、Hook和功能模块。
可用脚本:
scripts/create_component.py- 组件文件(.tsx)
- TypeScript类型文件(.types.ts)
- CSS模块(.module.css)
- 测试文件(.test.tsx)
- Storybook故事文件(.stories.tsx) [可选]
- 用于清晰导入的索引文件
bash
undefinedCreate a basic component
创建基础组件
python scripts/create_component.py Button --type component
python scripts/create_component.py Button --type component
Create a page component with lazy loading
创建带懒加载的页面组件
python scripts/create_component.py Dashboard --type page
python scripts/create_component.py Dashboard --type page
Create component with children prop
创建包含children属性的组件
python scripts/create_component.py Card --children
python scripts/create_component.py Card --children
Create component with Storybook story
创建带Storybook故事的组件
python scripts/create_component.py Button --story
python scripts/create_component.py Button --story
Without tests
不生成测试文件
python scripts/create_component.py SimpleComponent --no-tests
**When to use:**
- Creating any new component
- Setting up new feature modules
- Need consistent component structure
- Want to speed up development
**`scripts/create_hook.py`**
Generates custom hooks with templates for common patterns:
- State management hooks
- Effect hooks
- Data fetching hooks
- LocalStorage hooks
- Debounce hooks
- Interval hooks
```bashpython scripts/create_component.py SimpleComponent --no-tests
**适用场景:**
- 创建任何新组件
- 搭建新功能模块
- 需要一致的组件结构
- 想要提升开发速度
**`scripts/create_hook.py`**
生成包含常见模式模板的自定义Hook:
- 状态管理Hook
- 副作用Hook
- 数据获取Hook
- LocalStorage Hook
- 防抖Hook
- 定时器Hook
```bashCreate custom hook
创建自定义Hook
python scripts/create_hook.py useAuth --type custom
python scripts/create_hook.py useAuth --type custom
Create data fetching hook
创建数据获取Hook
python scripts/create_hook.py useUserData --type fetch
python scripts/create_hook.py useUserData --type fetch
Create localStorage hook
创建LocalStorage Hook
python scripts/create_hook.py useSettings --type localStorage
python scripts/create_hook.py useSettings --type localStorage
Create debounce hook
创建防抖Hook
python scripts/create_hook.py useSearchDebounce --type debounce
**When to use:**
- Extracting reusable logic
- Creating custom state management
- Need common hook patterns
- Want hook with tests automaticallypython scripts/create_hook.py useSearchDebounce --type debounce
**适用场景:**
- 提取可复用逻辑
- 创建自定义状态管理
- 需要常见Hook模式
- 想要自动生成带测试的Hook3. Performance Optimization
3. 性能优化
Optimize React applications for maximum performance and minimal bundle size.
Reference:
references/performance_optimization.mdThis guide covers:
- React rendering optimization: React.memo(), useMemo(), useCallback()
- Code splitting: React.lazy(), route-based splitting, component splitting
- Virtualization: Long list optimization with react-window
- Debouncing & throttling: Input optimization, scroll handling
- Vite build optimization: Chunk splitting, minification, compression
- Image optimization: WebP/AVIF, lazy loading, responsive images
- Network optimization: API request optimization, prefetching
- CSS performance: CSS Modules vs CSS-in-JS, critical CSS
- Web Vitals tracking: Measuring LCP, FID, CLS
When to consult:
- App feels slow or laggy
- Large bundle sizes
- Long initial load time
- User asks about optimization
- Preparing for production deployment
- Performance audit reveals issues
Quick Performance Checklist:
- Run to identify large dependencies
python scripts/analyze_bundle.py - Check for optimization strategies
references/performance_optimization.md - Apply code splitting for routes:
React.lazy(() => import('./Page')) - Memoize expensive components:
React.memo(Component) - Use for expensive calculations
useMemo() - Implement virtualization for long lists (react-window)
- Optimize images (WebP, lazy loading)
- Review Vite config in
assets/vite.config.optimized.ts
scripts/analyze_bundle.pybash
undefined优化React应用以实现最高性能和最小包体积。
参考文档:
references/performance_optimization.md本指南涵盖:
- React渲染优化:React.memo(), useMemo(), useCallback()
- 代码分割:React.lazy(), 基于路由的分割、基于组件的分割
- 虚拟化:使用react-window优化长列表
- 防抖与节流:输入优化、滚动处理
- Vite构建优化: chunk分割、压缩、代码混淆
- 图片优化:WebP/AVIF格式、懒加载、响应式图片
- 网络优化:API请求优化、预获取
- CSS性能:CSS模块vs CSS-in-JS、关键CSS
- Web Vitals追踪:测量LCP、FID、CLS
适用场景:
- 应用感觉缓慢或卡顿
- 包体积过大
- 初始加载时间过长
- 用户询问优化相关问题
- 准备生产部署
- 性能审计发现问题
快速性能检查清单:
- 运行识别大型依赖
python scripts/analyze_bundle.py - 查看获取优化策略
references/performance_optimization.md - 为路由应用代码分割:
React.lazy(() => import('./Page')) - 对开销大的组件进行记忆化:
React.memo(Component) - 使用处理开销大的计算
useMemo() - 为长列表实现虚拟化(react-window)
- 优化图片(WebP格式、懒加载)
- 查看中的Vite配置
assets/vite.config.optimized.ts
scripts/analyze_bundle.pybash
undefinedRun bundle analysis
运行包分析
python scripts/analyze_bundle.py
**What it analyzes:**
- Package.json dependencies (identifies large libraries)
- Import patterns (suggests better imports for tree-shaking)
- Build output (bundle sizes, chunk distribution)
- Provides specific optimization recommendations
**When to run:**
- Before production deployment
- After adding new dependencies
- When bundle size increases unexpectedly
- Regular monthly audits
- Performance optimization sessionspython scripts/analyze_bundle.py
**分析内容:**
- Package.json依赖(识别大型库)
- 导入模式(为摇树优化建议更好的导入方式)
- 构建输出(包大小、chunk分布)
- 提供具体的优化建议
**运行时机:**
- 生产部署前
- 添加新依赖后
- 包体积意外增加时
- 每月定期审计
- 性能优化会话4. Production-Ready Configuration
4. 生产就绪配置
Deploy optimized Vite configurations and project setups.
Assets available:
assets/vite.config.optimized.ts- Path aliases: Clean imports (@/components, @/hooks, etc.)
- Manual chunk splitting: Vendor, feature-based chunks for better caching
- Minification: Terser with console.log removal in production
- Bundle analyzer: Visualize bundle composition
- Asset optimization: Image handling, font loading
- Development proxy: API proxy configuration
- Source maps: Conditional source map generation
- CSS code splitting: Automatic CSS chunking
When to use:
- Starting new project
- Optimizing existing build
- Setting up production pipeline
- Need better caching strategy
- Want to analyze bundle
How to use:
- Copy to project root
assets/vite.config.optimized.ts - Install dependencies:
npm install -D rollup-plugin-visualizer - Customize manual chunks for your features
- Run build with analyzer:
npm run build:analyze
assets/tsconfig.optimized.json- Strict mode enabled: Catch more errors at compile time
- Path aliases: Matching Vite config
- Optimal compiler options: For Vite and modern React
- Unused code detection: noUnusedLocals, noUnusedParameters
- Type safety: noImplicitReturns, noUncheckedIndexedAccess
When to use:
- Starting new TypeScript project
- Want stricter type checking
- Need path aliases
- Improving type safety
assets/package.json.example- All recommended scripts: dev, build, test, lint, format
- Essential dependencies: React, React DOM, Router
- Dev dependencies: TypeScript, ESLint, Prettier, Vitest
- Recommended optional dependencies: Categorized by use case
- Husky & lint-staged setup: Pre-commit hooks
- CI/CD scripts: For automated pipelines
When to use:
- Starting new project
- Need script recommendations
- Setting up CI/CD
- Want git hooks
- Need package reference
assets/project-structure-example.md- Full directory tree: Feature-based architecture
- Key file examples: App.tsx, router, providers, API setup
- Configuration examples: vitest, eslint, prettier
- Test setup: Testing utilities and mocks
- Scaling guidelines: How to grow the structure
When to use:
- Starting new project from scratch
- Need structure reference
- Refactoring existing project
- Teaching team about organization
- Creating project templates
部署经过优化的Vite配置和项目设置。
可用资源:
assets/vite.config.optimized.ts- 路径别名:清晰的导入方式(@/components, @/hooks等)
- 手动chunk分割:按供应商、功能分割chunk以实现更好的缓存
- 压缩:生产环境移除console.log的Terser配置
- 包分析器:可视化包组成
- 资源优化:图片处理、字体加载
- 开发代理:API代理配置
- Source maps:条件式生成Source map
- CSS代码分割:自动CSS chunking
适用场景:
- 启动新项目
- 优化现有构建流程
- 搭建生产流水线
- 需要更好的缓存策略
- 想要分析包结构
使用方法:
- 将复制到项目根目录
assets/vite.config.optimized.ts - 安装依赖:
npm install -D rollup-plugin-visualizer - 为你的功能自定义手动chunk
- 使用分析器运行构建:
npm run build:analyze
assets/tsconfig.optimized.json- 启用严格模式:编译时捕获更多错误
- 路径别名:与Vite配置匹配
- 最优编译器选项:适用于Vite和现代React
- 未使用代码检测:noUnusedLocals、noUnusedParameters
- 类型安全:noImplicitReturns、noUncheckedIndexedAccess
适用场景:
- 启动新的TypeScript项目
- 想要更严格的类型检查
- 需要路径别名
- 提升类型安全性
assets/package.json.example- 所有推荐脚本:dev、build、test、lint、format
- 核心依赖:React、React DOM、Router
- 开发依赖:TypeScript、ESLint、Prettier、Vitest
- 推荐可选依赖:按使用场景分类
- Husky & lint-staged设置:提交前钩子
- CI/CD脚本:用于自动化流水线
适用场景:
- 启动新项目
- 需要脚本建议
- 搭建CI/CD
- 想要Git钩子
- 需要包参考
assets/project-structure-example.md- 完整目录树:基于功能的架构
- 关键文件示例:App.tsx、路由、提供者、API设置
- 配置示例:vitest、eslint、prettier
- 测试设置:测试工具和模拟
- 扩展指南:如何扩展结构
适用场景:
- 从零开始启动新项目
- 需要结构参考
- 重构现有项目
- 向团队传授组织方式
- 创建项目模板
5. React Best Practices & Patterns
5. React最佳实践与模式
Implement modern React patterns and avoid common pitfalls.
Reference:
references/best_practices.mdThis guide covers:
- Component patterns: Compound components, render props, HOC, custom hooks
- TypeScript best practices: Typing components, hooks, events, generic components
- Error handling: Error boundaries, async error handling
- Form handling: Controlled components, validation, form libraries
- Testing: Component testing, hook testing, mocking
- Common anti-patterns: What to avoid and why
- Accessibility: a11y best practices, ARIA, keyboard navigation
When to consult:
- Implementing complex component patterns
- Need TypeScript guidance
- Setting up error handling
- Creating forms
- Writing tests
- User asks "what's the best way to...?"
- Code review requests
- Teaching React patterns
Pattern Decision Guide:
- Compound Components: For flexible, composable UI (Tabs, Accordion)
- Custom Hooks: Extract and reuse logic (useAuth, useDebounce)
- Context + Hook: Share state across tree (Theme, Auth)
- Render Props: Share code with render control (rare, mostly replaced by hooks)
- HOC: Add cross-cutting concerns (rare, mostly replaced by hooks)
实施现代React模式,避免常见陷阱。
参考文档:
references/best_practices.md本指南涵盖:
- 组件模式:复合组件、渲染属性、高阶组件(HOC)、自定义Hook
- TypeScript最佳实践:组件类型定义、Hook类型、事件类型、泛型组件
- 错误处理:错误边界、异步错误处理
- 表单处理:受控组件、验证、表单库
- 测试:组件测试、Hook测试、模拟
- 常见反模式:需要避免的做法及原因
- 可访问性:a11y最佳实践、ARIA、键盘导航
适用场景:
- 实现复杂组件模式
- 需要TypeScript指导
- 搭建错误处理
- 创建表单
- 编写测试
- 用户询问“最好的实现方式是...?”
- 代码审查请求
- 教授React模式
模式决策指南:
- 复合组件:用于灵活、可组合的UI(标签页、折叠面板)
- 自定义Hook:提取和复用逻辑(useAuth、useDebounce)
- Context + Hook:在组件树间共享状态(主题、权限)
- 渲染属性:共享代码并控制渲染(已很少使用,多被Hook替代)
- 高阶组件:添加横切关注点(已很少使用,多被Hook替代)
6. TypeScript Excellence
6. TypeScript进阶
Write type-safe React code with proper TypeScript patterns.
Key TypeScript patterns in :
references/best_practices.md- Component prop typing (interfaces vs types)
- Event handler typing
- Ref typing
- Generic component typing
- Hook typing
- Type guards and narrowing
- Utility types
When user asks about TypeScript:
- Read relevant section in
references/best_practices.md - Provide type-safe examples
- Explain the "why" behind the pattern
- Show both the wrong and right way
Common TypeScript Questions:
- "How do I type this component?" → Component Props Typing section
- "How do I type an event handler?" → Hooks Typing section
- "How do I make a generic component?" → Generic Components section
- "How do I type a ref?" → Hooks Typing section
使用正确的TypeScript模式编写类型安全的React代码。
references/best_practices.md- 组件属性类型定义(接口vs类型别名)
- 事件处理器类型
- Ref类型
- 泛型组件类型
- Hook类型
- 类型守卫与类型收窄
- 工具类型
当用户询问TypeScript相关问题时:
- 查看中的相关章节
references/best_practices.md - 提供类型安全的示例
- 解释模式背后的原因
- 展示错误和正确的实现方式
常见TypeScript问题:
- “我该如何为这个组件定义类型?” → 组件属性类型定义章节
- “我该如何为事件处理器定义类型?” → Hook类型章节
- “我该如何创建泛型组件?” → 泛型组件章节
- “我该如何为Ref定义类型?” → Hook类型章节
7. Testing Strategy
7. 测试策略
Implement comprehensive testing for React applications.
Testing patterns in :
references/best_practices.md- Component testing with React Testing Library
- Custom hook testing
- Test utilities and setup
- Mocking strategies
- Integration testing
Testing Philosophy:
- Test user behavior, not implementation
- Test what the user sees and does
- Mock external dependencies
- Use descriptive test names
- Arrange-Act-Assert pattern
When user needs testing help:
- Check if component generator created tests:
scripts/create_component.py - Reference testing section in
references/best_practices.md - Show test setup in
assets/project-structure-example.md - Provide specific test examples for their use case
为React应用实施全面的测试方案。
references/best_practices.md- 使用React Testing Library进行组件测试
- 自定义Hook测试
- 测试工具和设置
- 模拟策略
- 集成测试
测试理念:
- 测试用户行为,而非实现细节
- 测试用户看到和操作的内容
- 模拟外部依赖
- 使用描述性的测试名称
- 遵循Arrange-Act-Assert模式
当用户需要测试帮助时:
- 检查组件生成器是否创建了测试:
scripts/create_component.py - 参考中的测试章节
references/best_practices.md - 查看中的测试设置
assets/project-structure-example.md - 为他们的使用场景提供具体的测试示例
8. State Management Guidance
8. 状态管理指导
Choose and implement the right state management solution.
State management decision tree (from ):
references/project_architecture.mdIs it server data (from API)?
└─ Yes → TanStack Query (React Query)
Is it local to a component?
└─ Yes → useState
Is it shared between 2-3 components?
└─ Yes → Lift state up (props)
Is it global but simple (theme, auth)?
└─ Yes → Context + useState
Is it global and complex?
├─ Small/medium app → Zustand
└─ Large app with complex async → Redux ToolkitWhen to consult :
references/project_architecture.md- Choosing state management solution
- Need code examples for each approach
- Understanding trade-offs
- Migrating state management
- Performance issues with re-renders
选择并实施合适的状态管理方案。
状态管理决策树(来自):
references/project_architecture.md是否是服务器数据(来自API)?
└─ 是 → TanStack Query (React Query)
是否是组件局部状态?
└─ 是 → useState
是否在2-3个组件间共享?
└─ 是 → 状态提升(通过props)
是否是全局但简单的状态(主题、权限)?
└─ 是 → Context + useState
是否是全局且复杂的状态?
├─ 中小型应用 → Zustand
└─ 大型复杂异步应用 → Redux Toolkit适用场景:
- 选择状态管理方案
- 需要每种方案的代码示例
- 理解权衡
- 迁移状态管理
- 重渲染导致的性能问题
Workflow Examples
工作流示例
Example 1: "Help me start a new React project with best practices"
示例1:“帮我用最佳实践启动一个新的React项目”
-
Understand requirements:
- Ask about: Project size, features, state needs, team size
- Determine: Which patterns to use, structure complexity
-
Provide structure:
- Show
assets/project-structure-example.md - Explain feature-based vs simpler architecture
- Recommend based on project size
- Show
-
Set up configuration:
- Copy
assets/vite.config.optimized.ts - Copy
assets/tsconfig.optimized.json - Reference for scripts
assets/package.json.example
- Copy
-
Generate initial components:bash
# Create basic UI components python scripts/create_component.py Button --type component --story python scripts/create_component.py Input --type component # Create pages python scripts/create_component.py HomePage --type page # Create hooks python scripts/create_hook.py useAuth --type custom -
Explain next steps:
- Set up git hooks (husky)
- Configure ESLint and Prettier
- Set up testing
- Create initial routes
-
理解需求:
- 询问:项目规模、功能、状态需求、团队规模
- 确定:使用哪种模式、结构复杂度
-
提供结构:
- 展示
assets/project-structure-example.md - 解释基于功能vs更简单的架构
- 根据项目规模给出推荐
- 展示
-
设置配置:
- 复制
assets/vite.config.optimized.ts - 复制
assets/tsconfig.optimized.json - 参考获取脚本
assets/package.json.example
- 复制
-
生成初始组件:bash
# 创建基础UI组件 python scripts/create_component.py Button --type component --story python scripts/create_component.py Input --type component # 创建页面 python scripts/create_component.py HomePage --type page # 创建Hook python scripts/create_hook.py useAuth --type custom -
解释后续步骤:
- 设置Git钩子(husky)
- 配置ESLint和Prettier
- 设置测试
- 创建初始路由
Example 2: "My React app is slow, how do I optimize it?"
示例2:“我的React应用很慢,该怎么优化?”
-
Analyze current state:bash
# Run bundle analyzer python scripts/analyze_bundle.py -
Review analysis output:
- Identify large dependencies
- Check for duplicates
- Review import patterns
-
Consult optimization guide:
- Read
references/performance_optimization.md - Focus on relevant sections based on analysis
- Read
-
Apply optimizations (in order of impact):
- Code splitting: Implement lazy loading for routes
- Remove large dependencies: Suggest lighter alternatives
- Memoization: Add React.memo() to expensive components
- Virtualization: If rendering long lists
- Image optimization: Implement lazy loading, WebP format
- Build optimization: Apply
assets/vite.config.optimized.ts
-
Measure improvement:
- Run build before and after
- Compare bundle sizes
- Test Web Vitals
-
分析当前状态:bash
# 运行包分析器 python scripts/analyze_bundle.py -
查看分析输出:
- 识别大型依赖
- 检查重复依赖
- 查看导入模式
-
参考优化指南:
- 阅读
references/performance_optimization.md - 根据分析结果聚焦相关章节
- 阅读
-
应用优化(按影响优先级排序):
- 代码分割:为路由实现懒加载
- 移除大型依赖:建议更轻量的替代方案
- 记忆化:为开销大的组件添加React.memo()
- 虚拟化:如果渲染长列表
- 图片优化:实现懒加载、WebP格式
- 构建优化:应用
assets/vite.config.optimized.ts
-
衡量改进效果:
- 优化前后分别运行构建
- 比较包体积
- 测试Web Vitals
Example 3: "How should I organize my growing React project?"
示例3:“我该如何组织不断增长的React项目?”
-
Assess current size:
- Ask: How many components? How many features?
- Determine: Current pain points
-
Reference architecture guide:
- Read
references/project_architecture.md - Section: "Optimal Folder Structure"
- Read
-
Recommend structure:
- Small (<10 components): Flat structure
- Medium (10-50): Feature folders + shared components
- Large (50+): Full feature-based architecture
-
Show concrete example:
- Display relevant section from
assets/project-structure-example.md - Explain each folder's purpose
- Display relevant section from
-
Provide migration path:
- Don't refactor everything at once
- Start with new features in new structure
- Gradually migrate old code
-
评估当前规模:
- 询问:有多少组件?多少功能?
- 确定:当前痛点
-
参考架构指南:
- 阅读
references/project_architecture.md - 章节:“最优文件夹结构”
- 阅读
-
推荐结构:
- 小型(<10个组件):扁平结构
- 中型(10-50个):功能文件夹+共享组件
- 大型(50+个):完整的基于功能的架构
-
展示具体示例:
- 展示中的相关章节
assets/project-structure-example.md - 解释每个文件夹的用途
- 展示
-
提供迁移路径:
- 不要一次性重构所有代码
- 新功能使用新结构
- 逐步迁移旧代码
Example 4: "I need to create many similar components"
示例4:“我需要创建很多类似的组件”
-
Use component generator:bash
# Generate multiple components at once python scripts/create_component.py UserCard --type component python scripts/create_component.py ProductCard --type component python scripts/create_component.py OrderCard --type component -
Explain structure:
- Show generated files
- Explain each file's purpose
- Customize as needed
-
Create shared patterns:
- Extract common props to shared type
- Create base Card component
- Use composition pattern
-
Reference patterns guide:
- Show compound component pattern from
references/best_practices.md - Demonstrate component composition
- Show compound component pattern from
-
使用组件生成器:bash
# 一次性生成多个组件 python scripts/create_component.py UserCard --type component python scripts/create_component.py ProductCard --type component python scripts/create_component.py OrderCard --type component -
解释结构:
- 展示生成的文件
- 解释每个文件的用途
- 根据需要自定义
-
创建共享模式:
- 将公共属性提取到共享类型
- 创建基础Card组件
- 使用组合模式
-
参考模式指南:
- 展示中的复合组件模式
references/best_practices.md - 演示组件组合
- 展示
Example 5: "Help me set up testing for my React app"
示例5:“帮我为React应用设置测试”
-
Reference testing setup:
- Show
assets/project-structure-example.md - Section: "src/test/" folder structure
- Show
-
Set up test utilities:
- Copy test setup from example
- Configure vitest.config.ts
- Create test utilities (render with providers)
-
Generate components with tests:bash
# Components come with tests by default python scripts/create_component.py Button -
Explain testing patterns:
- Reference
references/best_practices.md - Section: "Testing Best Practices"
- Show component and hook testing examples
- Reference
-
Set up CI/CD:
- Add test scripts from
assets/package.json.example - Configure pre-commit hooks
- Set up GitHub Actions
- Add test scripts from
-
参考测试设置:
- 展示
assets/project-structure-example.md - 章节:“src/test/”文件夹结构
- 展示
-
设置测试工具:
- 复制示例中的测试设置
- 配置vitest.config.ts
- 创建测试工具(带提供者的render函数)
-
生成带测试的组件:bash
# 默认生成带测试的组件 python scripts/create_component.py Button -
解释测试模式:
- 参考
references/best_practices.md - 章节:“测试最佳实践”
- 展示组件和Hook测试示例
- 参考
-
设置CI/CD:
- 从添加测试脚本
assets/package.json.example - 配置提交前钩子
- 设置GitHub Actions
- 从
Best Practices for Using This Skill
使用本技能的最佳实践
Be Comprehensive
保持全面
- Don't just answer questions - provide complete solutions
- Show file structure, configuration, and examples
- Explain the "why" behind recommendations
- 不要只回答问题 - 提供完整解决方案
- 展示文件结构、配置和示例
- 解释建议背后的原因
Use All Resources
充分利用所有资源
- Scripts: Generate code for consistency
- References: Deep dives into concepts
- Assets: Production-ready configs and examples
- 脚本:生成代码以保持一致性
- 参考文档:深入讲解概念
- 资源文件:生产就绪的配置和示例
Follow This Order
遵循以下步骤
- Understand: Ask clarifying questions
- Reference: Consult relevant documentation
- Generate: Use scripts when applicable
- Explain: Teach the pattern/concept
- Provide: Give complete working examples
- 理解:提出澄清问题
- 参考:查阅相关文档
- 生成:适用时使用脚本
- 解释:教授模式/概念
- 提供:给出完整的可运行示例
Prioritize Performance
优先考虑性能
- Proactively suggest optimizations
- Run bundle analyzer regularly
- Recommend lazy loading by default
- Use optimized configurations
- 主动建议优化
- 定期运行包分析器
- 默认推荐懒加载
- 使用优化后的配置
Teach Best Practices
传授最佳实践
- Show the wrong way vs the right way
- Explain trade-offs
- Reference TypeScript strict mode
- Encourage testing
- 展示错误和正确的实现方式
- 解释权衡
- 参考TypeScript严格模式
- 鼓励测试
Stay Organized
保持组织性
- Recommend feature-based structure early
- Use path aliases from the start
- Establish naming conventions
- Plan for scale
- 尽早推荐基于功能的结构
- 从一开始就使用路径别名
- 建立命名规范
- 为扩展做规划
Reference Documentation
参考文档
references/project_architecture.md
references/project_architecture.md
Read when:
- Structuring new project
- Organizing existing project
- Choosing state management
- Setting up imports
- User asks "how should I organize...?"
Key sections:
- Optimal Folder Structure (2 patterns)
- Naming Conventions
- Component Organization Patterns
- State Management Strategies
- Import Strategies
- Decision Matrix
阅读时机:
- 构建新项目结构
- 组织现有项目
- 选择状态管理
- 设置导入
- 用户询问“我该如何组织...?”
关键章节:
- 最优文件夹结构(2种模式)
- 命名规范
- 组件组织模式
- 状态管理策略
- 导入策略
- 决策矩阵
references/performance_optimization.md
references/performance_optimization.md
Read when:
- App is slow
- Large bundle sizes
- Optimizing for production
- User asks about performance
- Before deployment
Key sections:
- React Rendering Optimization (memo, useMemo, useCallback)
- Code Splitting
- Virtualization
- Vite Build Optimization
- Image Optimization
- Network Performance
- CSS Performance
- Web Vitals Tracking
阅读时机:
- 应用缓慢
- 包体积过大
- 为生产环境优化
- 用户询问性能相关问题
- 部署前
关键章节:
- React渲染优化(memo、useMemo、useCallback)
- 代码分割
- 虚拟化
- Vite构建优化
- 图片优化
- 网络性能
- CSS性能
- Web Vitals追踪
references/best_practices.md
references/best_practices.md
Read when:
- Implementing patterns
- TypeScript questions
- Error handling setup
- Form implementation
- Testing questions
- Code review
Key sections:
- Component Patterns (5 patterns)
- TypeScript Best Practices
- Error Handling Patterns
- Form Handling
- Testing Best Practices
- Common Anti-Patterns
- Accessibility
阅读时机:
- 实现模式
- TypeScript相关问题
- 错误处理设置
- 表单实现
- 测试相关问题
- 代码审查
关键章节:
- 组件模式(5种)
- TypeScript最佳实践
- 错误处理模式
- 表单处理
- 测试最佳实践
- 常见反模式
- 可访问性
Quick Reference
快速参考
Common Commands
常用命令
bash
undefinedbash
undefinedGenerate component
生成组件
python scripts/create_component.py ComponentName --type component
python scripts/create_component.py ComponentName --type component
Generate page
生成页面
python scripts/create_component.py PageName --type page
python scripts/create_component.py PageName --type page
Generate hook
生成Hook
python scripts/create_hook.py useHookName --type custom
python scripts/create_hook.py useHookName --type custom
Analyze bundle
分析包
python scripts/analyze_bundle.py
undefinedpython scripts/analyze_bundle.py
undefinedCommon Questions
常见问题
- "How do I structure my project?" →
references/project_architecture.md - "How do I optimize performance?" → + run
references/performance_optimization.mdanalyze_bundle.py - "What pattern should I use?" →
references/best_practices.md - "How do I configure Vite?" →
assets/vite.config.optimized.ts - "What should my package.json look like?" →
assets/package.json.example
- “我该如何构建项目结构?” →
references/project_architecture.md - “我该如何优化性能?” → + 运行
references/performance_optimization.mdanalyze_bundle.py - “我该使用哪种模式?” →
references/best_practices.md - “我该如何配置Vite?” →
assets/vite.config.optimized.ts - “我的package.json应该是什么样的?” →
assets/package.json.example
File Structure Priority
文件结构优先级
- Feature-based (large apps) - See
references/project_architecture.md - Component-based (medium apps) - See simpler structure
- Flat (small apps) - Minimal organization
- 基于功能(大型应用)- 查看
references/project_architecture.md - 基于组件(中型应用)- 查看更简单的结构
- 扁平结构(小型应用)- 最小化组织
Performance Priority
性能优化优先级
- Code splitting (routes first)
- Remove large dependencies
- Lazy loading (images, components)
- Memoization (expensive components)
- Virtualization (long lists)
- 代码分割(优先处理路由)
- 移除大型依赖
- 懒加载(图片、组件)
- 记忆化(开销大的组件)
- 虚拟化(长列表)
State Management Priority
状态管理优先级
- Server data → React Query
- Local state → useState
- Shared simple state → Context
- Global complex state → Zustand or Redux Toolkit
- 服务器数据 → React Query
- 局部状态 → useState
- 简单全局状态 → Context
- 复杂全局状态 → Zustand或Redux Toolkit
When NOT to Use This Skill
不适用场景
- Non-React frameworks: Next.js has its own patterns (use Next.js skill)
- React Native: Mobile has different patterns
- Class components: Focus is on modern functional components
- Non-Vite build tools: Webpack/Parcel have different configs
- Backend development: This is frontend-focused
For these topics, provide general React guidance but acknowledge limitations.
- 非React框架:Next.js有自己的模式(使用Next.js相关技能)
- React Native:移动端有不同的模式
- 类组件:重点是现代函数式组件
- 非Vite构建工具:Webpack/Parcel有不同的配置
- 后端开发:本技能专注于前端
对于这些主题,提供通用React指导,但需说明局限性。
Success Metrics
成功指标
Your React + Vite project should achieve:
- ✅ Bundle size < 200KB (initial, gzipped)
- ✅ Lighthouse score > 90
- ✅ All tests passing
- ✅ No ESLint errors
- ✅ Consistent file structure
- ✅ Type-safe (TypeScript strict mode)
- ✅ Fast build times (< 30s for production)
- ✅ Fast HMR (< 100ms)
你的React + Vite项目应达到:
- ✅ 初始包体积 < 200KB(gzipped)
- ✅ Lighthouse得分 > 90
- ✅ 所有测试通过
- ✅ 无ESLint错误
- ✅ 一致的文件结构
- ✅ 类型安全(TypeScript严格模式)
- ✅ 快速构建时间(生产环境<30秒)
- ✅ 快速HMR(<100ms)