react-vite-best-practices — скилл для Claude Code: правила React
Скилл с 23 правилами оптимизации React-приложений на Vite: сборка, code splitting, HMR, ассеты, переменные окружения и анализ бандла. Пригодится, когда агент пишет или ревьюит компоненты.
npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a claude-codeЧто делает react-vite-best-practices
Скилл разбит на 6 категорий по приоритету. Первые две — критические: оптимизация сборки (manual chunks, минификация, tree shaking, сжатие, хеширование ассетов) и code splitting (ленивые маршруты через React.lazy(), границы Suspense, динамические импорты, префетч чанков). Дальше идут разработка, работа с ассетами, конфигурация окружения и анализ бандла.
Каждое правило лежит отдельным файлом в rules/, например rules/build-manual-chunks.md или rules/split-route-lazy.md. Внутри — объяснение и примеры кода. Есть готовый vite.config.ts с алиасами, manualChunks для вендоров и настройкой optimizeDeps, а также пример типизации переменных через vite-env.d.ts. Полный свод правил собран в AGENTS.md.
Одно из правил прямо запрещает выносить секреты в клиентский код: всё, что начинается с VITE_, попадает в бандл и видно в браузере. Если в проекте уже есть свой набор конвенций по Vite, скилл может спорить с ним — тогда решайте, чьи правила главнее, до того как агент начнёт править конфиг.
Какие задачи решает
- настроить manual chunks, чтобы вендоры не попадали в один бандл с кодом приложения
- разбить маршруты через React.lazy() и расставить границы Suspense
- ускорить старт dev-сервера через optimizeDeps
- разобраться, какие переменные окружения утекают в клиентский бандл
- посмотреть, из чего состоит бандл, через rollup-plugin-visualizer
Примеры запросов агенту
- Посмотри мой vite.config.ts и скажи, что тут можно улучшить по правилам react-vite-best-practices
- Разбей маршруты в приложении на ленивые чанки и подскажи, где поставить Suspense
- Проверь, не попадают ли секреты в клиентский код через переменные с префиксом VITE_
Как установить react-vite-best-practices
1Через Skills CLI (Vercel)
npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a claude-code2Вручную: положить файлы
~/.claude/skills/react-vite-best-practices/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/react-vite-best-practices/
1Через Skills CLI (Vercel)
npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a codex2Вручную: положить файлы
.agents/skills/react-vite-best-practices/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a cursor2Вручную: положить файлы
.cursor/skills/react-vite-best-practices/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install AsyrafHussin/agent-skills react-vite-best-practices2Вручную: положить файлы
.github/skills/react-vite-best-practices/SKILL.md1Через Skills CLI (Vercel)
npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a gemini-cli2Командой платформы
gemini skills install https://github.com/AsyrafHussin/agent-skills --path skills/react-vite-best-practicesВручную: положить файлы
.devin/skills/react-vite-best-practices/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о react-vite-best-practices
Как установить react-vite-best-practices в Claude?
Выполните npx skills add AsyrafHussin/agent-skills --skill react-vite-best-practices -a claude-code. После этого файл скилла окажется в ~/.claude/skills/react-vite-best-practices/SKILL.md.
Что делает этот скилл?
Даёт агенту набор из 23 правил по оптимизации React-приложений на Vite: сборка, code splitting, dev-сервер, ассеты, переменные окружения и анализ бандла. Агент подтягивает их, когда пишет, ревьюит или оптимизирует компоненты.
С какими платформами он совместим?
Кроме Claude есть установка для Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode. Для каждой платформы своя команда и свой путь к файлу скилла.
Исходный текст
SKILL.md · MIT
---
name: react-vite-best-practices
description: React and Vite performance optimization guidelines. Use when writing, reviewing, or optimizing React components built with Vite. Triggers on tasks involving Vite configuration, build optimization, code splitting, lazy loading, HMR, bundle size, or React performance.
license: MIT
metadata:
author: agent-skills
version: "2.0.0"
---
# React + Vite Best Practices
Comprehensive performance optimization guide for React applications built with Vite. Contains 23 rules across 6 categories for build optimization, code splitting, development performance, asset handling, environment configuration, and bundle analysis.
## Metadata
- **Version:** 2.0.0
- **Framework:** React + Vite
- **Rule Count:** 23 rules across 6 categories
- **License:** MIT
## 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 and HMR
- Handling images, fonts, SVGs, and static assets
- Managing environment variables across environments
- Analyzing bundle size and dependencies
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Build Optimization | CRITICAL | `build-` |
| 2 | Code Splitting | CRITICAL | `split-` |
| 3 | Development | HIGH | `dev-` |
| 4 | Asset Handling | HIGH | `asset-` |
| 5 | Environment Config | MEDIUM | `env-` |
| 6 | Bundle Analysis | MEDIUM | `bundle-` |
## Quick Reference
### 1. Build Optimization (CRITICAL)
- `build-manual-chunks` - Configure manual chunks for vendor separation
- `build-minification` - Minification with OXC (default) or Terser
- `build-target-modern` - Target modern browsers (baseline-widely-available)
- `build-sourcemaps` - Configure sourcemaps per environment
- `build-tree-shaking` - Ensure proper tree shaking with ESM
- `build-compression` - Gzip and Brotli compression
- `build-asset-hashing` - Content-based hashing for cache busting
### 2. Code Splitting (CRITICAL)
- `split-route-lazy` - Route-based splitting with React.lazy()
- `split-suspense-boundaries` - Strategic Suspense boundary placement
- `split-dynamic-imports` - Dynamic import() for heavy components
- `split-component-lazy` - Lazy load non-critical components
- `split-prefetch-hints` - Prefetch chunks on hover/idle/viewport
### 3. Development (HIGH)
- `dev-dependency-prebundling` - Configure optimizeDeps for faster starts
- `dev-fast-refresh` - React Fast Refresh patterns
- `dev-hmr-config` - HMR server configuration
### 4. Asset Handling (HIGH)
- `asset-image-optimization` - Image optimization and lazy loading
- `asset-svg-components` - SVGs as React components with SVGR
- `asset-fonts` - Web font loading strategy
- `asset-public-dir` - Public directory vs JavaScript imports
### 5. Environment Config (MEDIUM)
- `env-vite-prefix` - VITE_ prefix for client variables
- `env-modes` - Mode-specific environment files
- `env-sensitive-data` - Never expose secrets in client code
### 6. Bundle Analysis (MEDIUM)
- `bundle-visualizer` - Analyze bundles with rollup-plugin-visualizer
## Essential Configurations
### Recommended 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: 'baseline-widely-available',
sourcemap: false,
chunkSizeWarningLimit: 500,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
},
},
},
},
optimizeDeps: {
include: ['react', 'react-dom'],
},
server: {
port: 3000,
hmr: {
overlay: true,
},
},
})
```
### Route-Based Code Splitting
```typescript
import { lazy, Suspense } from 'react'
const Home = lazy(() => import('./pages/Home'))
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Settings = lazy(() => import('./pages/Settings'))
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
{/* Routes here */}
</Suspense>
)
}
```
### Environment Variables
```typescript
// src/vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string
readonly VITE_APP_TITLE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
```
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/build-manual-chunks.md
rules/split-route-lazy.md
rules/env-vite-prefix.md
```
## References
- [Vite Documentation](https://vite.dev)
- [React Documentation](https://react.dev)
- [Rollup Documentation](https://rollupjs.org)
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
© agent-skills · MIT · AsyrafHussin/agent-skills