Learn how to create custom slash commands for Claude Code, using the retired /new-component command as a worked example. Master prompt engineering techniques for building intelligent development automation tools.
What Are Slash Commands?
Section titled “What Are Slash Commands?”Slash commands are markdown files in .claude/commands/ that give Claude specific instructions for performing tasks. They’re essentially specialized prompts that execute when invoked with /command-name.
Traditional vs Slash Command Approach
Section titled “Traditional vs Slash Command Approach”Manual Approach:
You: "Create a React component called UserProfile with tests and stories"Claude: *May or may not follow project patterns* *Needs clarification questions* *Results vary based on interpretation*- Inconsistent results
- Requires explaining conventions
- Easy to forget steps
Automated Approach:
You: /new-component UserProfileClaude: *Follows exact project patterns* *No clarification needed* *Consistent results every time*- Same pattern every time
- Project conventions baked in
- Never forget a step
Key Benefits
Section titled “Key Benefits”Consistency
Same pattern every execution - no variation in quality or structure
Speed
No explaining project conventions - instant results
Completeness
Never forget a step - all requirements captured
Intelligence
Claude adapts to edge cases and validates input
Documentation
Command file documents the process for the team
Reusability
Any team member can use it - knowledge sharing
Anatomy of a Slash Command
Section titled “Anatomy of a Slash Command”Every slash command file has three essential parts:
1. YAML Frontmatter (Required)
Section titled “1. YAML Frontmatter (Required)”---description: Brief description shown in command listallowed-tools: - Write - Read - Edit - AskUserQuestionargument-hint: <arg1> [optional-arg]---Key Fields:
- description: One-line summary (shown when listing commands)
- allowed-tools: Which Claude tools the command can use
- argument-hint: Shows users expected argument format
2. Instructions Section
Section titled “2. Instructions Section”Clear, imperative instructions telling Claude exactly what to do:
## Instructions
1. **Parse arguments** - Extract component name - Validate format
2. **Generate files** - Use Write tool for each file - Follow templates below
3. **Report success** - List generated files - Provide next steps3. Reference Materials
Section titled “3. Reference Materials”Templates, examples, validation rules that Claude uses:
## Templates
### Component Template\`\`\`typescript// Template content with placeholders for component name\`\`\`
## Validation Rules- Must be PascalCase- No special characters
## ExamplesBasic: /command ExampleAdvanced: /command path/ExampleCase Study: /new-component
Section titled “Case Study: /new-component”Let’s analyze the /new-component command to understand effective prompt engineering. The command itself was
retired from .claude/commands/ in September 2026 after a usage audit found no invocations; its prompt is
reproduced here because it remains a good example of the structure.
YAML Frontmatter Design
Section titled “YAML Frontmatter Design”---description: Generate React component scaffold with test, story, and barrel export filesallowed-tools: - Write - Read - Edit - AskUserQuestion - Globargument-hint: <ComponentName> or <path/ComponentName>---Why These Choices?
Description
Clearly states what gets generated (not just “creates component”)
Tools
- Write: Create new files
- Read: Check for existing files
- Edit: Update barrel exports
- AskUserQuestion: Interactive mode
- Glob: Find existing components
Argument Hint
Shows both basic and nested usage patterns
Instruction Workflow
Section titled “Instruction Workflow”The command follows a numbered workflow:
-
Parse component name from arguments
- If provided: Extract name and path
- If not provided: Use AskUserQuestion
-
Validate component name
- Must be PascalCase
- Regex:
/^[A-Z][a-zA-Z0-9_]*$/ - Show helpful error if invalid
-
Determine paths
- Calculate all 4 file paths
- Component, test, story, barrel export
-
Check for collisions
- Use Read tool to check if exists
- Warn user if overwriting
-
Generate files
- Use Write tool with templates
- Replace
ComponentNameplaceholders with actual component name
-
Update barrel export
- Read existing index.ts
- Add new export
- Sort alphabetically
-
Report success
- Show checkmarks
- List files
- Provide next steps
Why This Works:
- ✅ Sequential: Clear order of operations
- ✅ Conditional: Handles missing arguments
- ✅ Defensive: Checks for collisions
- ✅ Complete: Doesn’t skip steps
- ✅ Helpful: Provides guidance at the end
Template Placeholders
Section titled “Template Placeholders”Templates use placeholder syntax for variable replacement:
export type ComponentNameProps = { children?: React.ReactNode className?: string}
export const ComponentName: React.FC<ComponentNameProps> = ({ children, className}) => { return <div className={className}>{children}</div>}Key Techniques:
ComponentNameplaceholders replaced with actual component name- Multiple placeholders in same template
- Includes project patterns (ComponentNameProps, displayName)
Validation with Examples
Section titled “Validation with Examples”## Validation Rules
**Component Name**:- Must be PascalCase (e.g., `UserProfile`, `LoginForm`)- No special characters except underscore- Cannot start with number- Regex: `/^[A-Z][a-zA-Z0-9_]*$/`
**Valid names**:- `UserProfile` ✅- `LoginForm` ✅- `EventCard` ✅
**Invalid names**:- `userProfile` ❌ (camelCase)- `user-profile` ❌ (kebab-case)- `User Profile` ❌ (contains space)Error Message Templates
Section titled “Error Message Templates”Provide error message templates for consistency:
If component name is invalid:\`\`\`❌ Invalid component name: "user-profile"
Component names must be PascalCase.
Valid examples: - UserProfile - LoginForm - EventCard
Please try again.\`\`\`This ensures Claude gives consistent, helpful errors with example input.
Prompt Engineering Techniques
Section titled “Prompt Engineering Techniques”1. Be Imperative and Specific
Section titled “1. Be Imperative and Specific”You should create a component file.Too vague - no details on how or where
1. **Generate component file**: - Use Write tool - Location: `src/components/react/ComponentName.tsx` - Use Component Template belowExplicit tool, location, and template reference (ComponentName is a placeholder)
2. Use Structured Lists
Section titled “2. Use Structured Lists”Parse the arguments, validate the name, create files, and report success.Run-on sentence - hard to follow
1. **Parse arguments** - Extract component name - Extract optional path
2. **Validate name** - Check PascalCase - Show error if invalid
3. **Create files** - Component - Test - Story
4. **Report success** - List files - Show next stepsClear hierarchy and sequence
3. Provide Examples
Section titled “3. Provide Examples”Component name must be PascalCase.No examples of what’s valid
Component name must be PascalCase.
**Valid**: `UserProfile`, `LoginForm`, `EventCard`**Invalid**: `userProfile`, `user-profile`, `User Profile`Clear examples of both valid and invalid
4. Include Templates
Section titled “4. Include Templates”Create a TypeScript component with props.Description only - no concrete example
### Component Template
```typescriptexport type ComponentNameProps = { children?: React.ReactNode}
export const ComponentName: React.FC<ComponentNameProps> = ({ children}) => { return <div>{children}</div>}```Exact code template with placeholders for ComponentName
5. Handle Edge Cases
Section titled “5. Handle Edge Cases”Create 4 files.No collision handling
5. **Check for collisions**: - Use Read tool to check if component exists - If exists, ask user to confirm overwrite - If user cancels, stop executionGraceful handling of existing files
6. Provide Context
Section titled “6. Provide Context”Use path aliases.No explanation why
## Important Notes
- **ALWAYS use path aliases** with `#` prefix - Example: `import X from '#components/react/X'`- **NEVER use relative imports** - Example: `import X from '../../components/X'`- This ensures consistency with project standardsContext and rationale included
7. Show Success Output
Section titled “7. Show Success Output”Report that files were created.No format specified
## Success Message Format
\`\`\`✅ Component scaffold created successfully!
Files generated: 📄 src/components/react/ComponentName.tsx 🧪 tests/components/ComponentName.react.test.tsx 📖 src/components/react/ComponentName.stories.tsx 📦 src/components/react/index.ts (updated)
Next steps: 1. Implement component logic 2. Write comprehensive tests 3. Run: npm run storybook\`\`\`Formatted template with emojis and next steps (ComponentName is a placeholder)
Common Patterns
Section titled “Common Patterns”Pattern 1: File Generation
Section titled “Pattern 1: File Generation”Simple file creation with validation:
## Instructions
1. **Parse arguments** - Extract filename from `$ARGUMENTS` - Validate format
2. **Generate file** - Use Write tool - Location: `src/filename.tsx` (filename is a placeholder) - Use template below
3. **Report success**
## Template
\`\`\`typescript// Generated file content\`\`\`Pattern 2: Multi-File Generation
Section titled “Pattern 2: Multi-File Generation”Creating multiple related files:
## Instructions
1. **Determine file paths** - Component: `src/components/Name.tsx` - Test: `tests/Name.test.tsx` - Story: `src/components/Name.stories.tsx`
2. **Generate all files** - Use Write tool for each - Replace Name placeholders in templates
## Templates
### Component Template\`\`\`typescript...\`\`\`
### Test Template\`\`\`typescript...\`\`\`Pattern 3: Interactive Input
Section titled “Pattern 3: Interactive Input”Prompting users when arguments missing:
## Instructions
1. **Check for arguments** - If provided, use directly - If missing, use AskUserQuestion
2. **Use AskUserQuestion** - Question: "What is the component name?" - Validate response - Re-prompt if invalid (max 3 times)Pattern 4: File Updates
Section titled “Pattern 4: File Updates”Modifying existing files safely:
## Instructions
1. **Read existing file** - Use Read tool - Parse current content
2. **Make updates** - Add new entry - Sort alphabetically - Preserve formatting
3. **Write updated file** - Use Edit or Write tool - Verify changesPattern 5: Validation + Feedback
Section titled “Pattern 5: Validation + Feedback”Input validation with helpful errors:
## Instructions
1. **Validate input** - Check against rules - If invalid, show error message - Provide examples of valid input - Allow retry
## Validation Rules
[Specific rules with regex]
## Error Messages
[Helpful error templates]Testing Your Command
Section titled “Testing Your Command”-
Create test file
Terminal window cat > .claude/commands/test-command.md << 'EOF'---description: Test commandallowed-tools:- Write---# Test Command1. Write a file to `/tmp/test.txt`2. Report success## TemplateHello from test command!EOF -
Invoke command
Terminal window /test-command -
Verify behavior
- Did it execute correctly?
- Did it follow instructions?
- Were errors handled gracefully?
- Is output helpful?
-
Test edge cases
Terminal window # Missing arguments/test-command# Invalid arguments/test-command invalid@name# Existing files/test-command ExistingComponent -
Refine instructions
Based on results, update:
- Clearer wording
- Better examples
- More validation
- Improved error messages
Troubleshooting
Section titled “Troubleshooting”Command Not Recognized
Section titled “Command Not Recognized”Solutions:
- Check file is in
.claude/commands/ - Verify filename is
my-command.md(matches command name) - Ensure YAML frontmatter is present
- Restart Claude Code or reload window
Command Doesn’t Follow Instructions
Section titled “Command Doesn’t Follow Instructions”Solutions:
- Make instructions more explicit and imperative
- Break complex steps into smaller sub-steps
- Use numbered lists for sequential operations
- Add examples showing expected behavior
- Include validation checkpoints
Command Produces Inconsistent Results
Section titled “Command Produces Inconsistent Results”Solutions:
- Reduce ambiguity in instructions
- Provide explicit templates (not descriptions)
- Include validation rules with regex
- Add error handling for edge cases
- Test with various inputs
Tools Not Working
Section titled “Tools Not Working”Solutions:
- Add tool to
allowed-toolsin frontmatter - Check tool name matches exactly (case-sensitive)
- Verify tool is available in Claude Code
Templates Not Replacing Placeholders
Section titled “Templates Not Replacing Placeholders”Solutions:
- Ensure instructions explicitly say “Replace placeholders with actual values”
- Use consistent placeholder syntax (e.g.,
ComponentName,filename) - Show examples of replacement in instructions
- Test placeholder names (avoid conflicts)
Best Practices Summary
Section titled “Best Practices Summary”Be Explicit
Don’t assume Claude knows project conventions
Provide Examples
Show don’t just tell
Include Templates
Exact code is better than descriptions
Validate Input
Check before generating
Handle Errors
Graceful failure with helpful messages
Report Progress
Show what was done
Provide Next Steps
Guide user after completion
Test Thoroughly
Try edge cases and invalid inputs
Document Well
Explain why, not just what
Iterate
Refine based on real usage
See Also
Section titled “See Also”CLAUDE.md
Project patterns and conventions reference
Claude Code Documentation
Official Claude Code documentation