Files
2025-11-29 18:48:03 +08:00

292 lines
7.0 KiB
Markdown

# Component Scaffolding Skill
This skill allows Claude to automatically scaffold UI components with all necessary files and boilerplate code when the context suggests a component needs to be created.
## When to Use This Skill
Claude should invoke this skill autonomously when:
- User mentions creating a new component
- Discussion involves building UI elements
- Task requires adding new views or pages
- User describes a component they need
- Code analysis shows a component is referenced but doesn't exist
## What This Skill Does
Automatically generates a complete component structure including:
1. Main component file with TypeScript
2. Styles file (CSS Module, SCSS, or styled-components)
3. Test file with basic tests
4. Storybook story (if Storybook is detected)
5. Type definitions file
6. Index file for clean exports
## Framework Detection
The skill detects the project framework and generates appropriate code:
- **React**: Functional components with hooks
- **Next.js**: React Server Components or Client Components as appropriate
- **Vue 3**: Composition API with script setup
## Input Parameters
When invoked, the skill expects:
- `componentName`: Name of the component (e.g., "UserCard", "LoginForm")
- `componentType`: Type of component ("page", "layout", "ui", "feature")
- `hasProps`: Whether the component accepts props
- `needsState`: Whether the component needs internal state
- `async`: Whether the component fetches data
## Generated Structure
### For React/Next.js Component:
```
ComponentName/
├── ComponentName.tsx # Main component
├── ComponentName.module.css # Styles (if using CSS Modules)
├── ComponentName.test.tsx # Unit tests
├── ComponentName.stories.tsx # Storybook (if applicable)
├── ComponentName.types.ts # TypeScript types
└── index.ts # Barrel export
```
### For Vue Component:
```
ComponentName/
├── ComponentName.vue # Main component
├── ComponentName.spec.ts # Unit tests
├── ComponentName.stories.ts # Storybook (if applicable)
└── index.ts # Export
```
## Component Template Features
All generated components include:
### 1. TypeScript Types
```typescript
export interface ComponentNameProps {
// Props with JSDoc comments
title: string
onAction?: () => void
}
```
### 2. Accessibility
```typescript
// Semantic HTML
<button
type="button"
aria-label="Descriptive label"
onClick={handleClick}
>
```
### 3. Documentation
```typescript
/**
* ComponentName - Brief description
*
* @param title - Description of title prop
* @param onAction - Optional callback function
*
* @example
* <ComponentName title="Hello" onAction={handleAction} />
*/
```
### 4. Error Boundaries (React)
```typescript
// For complex components
export class ComponentNameErrorBoundary extends Component {
// Error boundary implementation
}
```
### 5. Loading States
```typescript
if (isLoading) {
return <Skeleton />
}
```
### 6. Tests
```typescript
describe('ComponentName', () => {
it('renders correctly', () => {
render(<ComponentName title="Test" />)
expect(screen.getByText('Test')).toBeInTheDocument()
})
it('handles user interaction', async () => {
const handleAction = vi.fn()
render(<ComponentName title="Test" onAction={handleAction} />)
await userEvent.click(screen.getByRole('button'))
expect(handleAction).toHaveBeenCalled()
})
})
```
## Styling Approaches
The skill adapts to the project's styling method:
### CSS Modules
```typescript
import styles from './ComponentName.module.css'
return <div className={styles.container}>...</div>
```
### Tailwind CSS
```typescript
return <div className="flex items-center gap-4 p-4">...</div>
```
### Styled Components
```typescript
import styled from 'styled-components'
const Container = styled.div`
display: flex;
/* styles */
`
```
## Best Practices Included
1. **Atomic Design Principles**
- Atoms: Basic building blocks (Button, Input)
- Molecules: Simple combinations (SearchBar)
- Organisms: Complex components (Header, UserProfile)
- Templates: Page layouts
- Pages: Actual pages
2. **Component Composition**
- Prefer composition over prop drilling
- Use children for flexible layouts
- Create compound components when appropriate
3. **Performance Optimization**
- Memo components when needed
- Lazy load heavy components
- Optimize re-renders
4. **Code Organization**
- Hooks at the top
- Event handlers in the middle
- Render logic at the bottom
- Helper functions outside component or in utils
## Integration with Project
The skill:
- Reads project structure to determine correct location
- Detects existing component patterns and follows them
- Uses project's ESLint/Prettier configuration
- Imports from existing utility/helper files
- Follows existing naming conventions
## Advanced Features
### Context Integration
Automatically imports and uses context:
```typescript
const { user } = useAuth()
const { theme } = useTheme()
```
### Form Handling
Integrates with form libraries if detected:
```typescript
import { useForm } from 'react-hook-form'
const { register, handleSubmit, formState: { errors } } = useForm()
```
### Data Fetching
Uses project's data fetching approach:
```typescript
// TanStack Query
const { data, isLoading, error } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
})
// SWR
const { data, error, isLoading } = useSWR('/api/users', fetcher)
```
## Example Invocations
### Simple UI Component
```
User: "I need a card component to display user information"
Skill generates:
- UserCard.tsx with props for user data
- Styles with card layout
- Tests for rendering and interactions
- TypeScript types for user data
```
### Complex Feature Component
```
User: "Create a product listing page with filters"
Skill generates:
- ProductListing.tsx with state management
- Filter components
- Product card components
- API integration for fetching products
- Loading and error states
- Comprehensive tests
```
### Form Component
```
User: "Build a registration form"
Skill generates:
- RegistrationForm.tsx with validation
- Form fields (email, password, etc.)
- react-hook-form integration
- Error display
- Submit handling
- Accessibility attributes
- Tests for validation and submission
```
## Customization Options
Users can provide additional context:
- "with dark mode support"
- "mobile responsive"
- "with animations"
- "accessible for screen readers"
- "with loading skeleton"
The skill adapts the generated code accordingly.
## Error Handling
If the skill cannot determine:
- Framework: Asks the user
- Component location: Suggests based on type
- Styling approach: Uses project default or asks
## Output
After scaffolding, the skill provides:
1. Summary of created files
2. Import statement for using the component
3. Basic usage example
4. Notes on customization needed
5. Next steps (adding logic, styling, etc.)
This skill dramatically speeds up component creation while ensuring consistency and best practices across the codebase.