Master Claude Code in a Week (Part 2): Slash Commands

· 8 min read

This is the second part of the "Master Claude Code in a Week" series. In this article, we'll explore Slash Commands — a feature that lets you create custom commands to speed up your workflow.

What are Slash Commands?

Slash Commands are user-invoked shortcuts stored as Markdown files. When you type /command-name in Claude Code, it reads the corresponding Markdown file and executes the instructions inside.

┌─────────────────────────────────────────────────────────┐
│                    SLASH COMMANDS                        │
├─────────────────────────────────────────────────────────┤
│                                                          │
│   User types:  /optimize                                │
│                    │                                    │
│                    ▼                                    │
│   ┌────────────────────────────────┐                   │
│   │ .claude/commands/optimize.md   │                   │
│   │ ────────────────────────────── │                   │
│   │ # Optimize Code                │                   │
│   │                                │                   │
│   │ Analyze the current file for:  │                   │
│   │ - Performance issues           │                   │
│   │ - Code smells                  │                   │
│   │ - Optimization opportunities   │                   │
│   └────────────────────────────────┘                   │
│                    │                                    │
│                    ▼                                    │
│   Claude executes instructions from file               │
│                                                          │
└─────────────────────────────────────────────────────────┘

Key Characteristics

Criteria Value
Invocation Manual (/command-name)
Persistence Session only
File Location .claude/commands/ or ~/.claude/commands/
Format Markdown (.md)
Best For Quick shortcuts, repetitive tasks

Installation

Storage Locations

Project-level (current project only):

mkdir -p .claude/commands

Global (all projects):

mkdir -p ~/.claude/commands

Copy from claude-howto

# Clone repo if you haven't
git clone https://github.com/luongnv89/claude-howto.git

# Copy all slash commands
cp claude-howto/01-slash-commands/*.md .claude/commands/

Example Slash Commands

1. Optimize Code (/optimize)

File: .claude/commands/optimize.md

# Optimize Code

Analyze the current file or selected code for optimization opportunities.

## Instructions

1. **Performance Analysis**
   - Identify expensive operations
   - Find unnecessary loops or iterations
   - Check for redundant calculations
   - Look for memory leaks or inefficient memory usage

2. **Code Smells**
   - Detect duplicate code
   - Find overly complex methods
   - Identify magic numbers/strings
   - Check for proper error handling

3. **Best Practices**
   - Suggest modern language features
   - Recommend design pattern improvements
   - Check naming conventions
   - Verify SOLID principles

## Output Format

For each issue found, provide:
- **Location**: File and line number
- **Issue**: Description of the problem
- **Impact**: How it affects performance/maintainability
- **Solution**: Concrete fix with code example
- **Priority**: High/Medium/Low

## Constraints

- Focus on practical, impactful improvements
- Don't suggest micro-optimizations that reduce readability
- Consider the project's coding standards
- Maintain backward compatibility

Usage:

/optimize

2. PR Preparation (/pr)

File: .claude/commands/pr.md

# Prepare Pull Request

Generate a comprehensive pull request description for the current changes.

## Instructions

1. **Analyze Changes**
   - Review all modified files
   - Identify the type of change (feature/bugfix/refactor/docs)
   - Understand the context and purpose

2. **Generate PR Description**
   
   Use this template:
   
   ```markdown
   ## Summary
   [Brief description of what this PR does]

   ## Type of Change
   - [ ] Bug fix (non-breaking change that fixes an issue)
   - [ ] New feature (non-breaking change that adds functionality)
   - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
   - [ ] Documentation update

   ## Changes Made
   - [List specific changes]
   - [Include file names where relevant]

   ## Testing
   - [ ] Unit tests added/updated
   - [ ] Integration tests added/updated
   - [ ] Manual testing completed

   ## Screenshots (if applicable)
   [Add screenshots for UI changes]

   ## Checklist
   - [ ] Code follows project style guidelines
   - [ ] Self-review completed
   - [ ] Documentation updated
   - [ ] No new warnings introduced
  1. Review Suggestions
    • Identify potential reviewers based on file ownership
    • Suggest labels based on change type
    • Flag any breaking changes or migrations needed

Output

  • Complete PR description ready to paste
  • List of suggested reviewers
  • Recommended labels

**Usage**:

/pr


### 3. Generate API Docs (`/generate-api-docs`)

**File**: `.claude/commands/generate-api-docs.md`

```markdown
# Generate API Documentation

Automatically generate comprehensive API documentation for the current file or module.

## Instructions

1. **Scan the Code**
   - Identify all public classes, methods, and functions
   - Extract parameters, return types, and exceptions
   - Find existing docstrings or comments

2. **Generate Documentation**

   For each public endpoint/method:
   
   ```markdown
   ## `methodName(param1, param2)`
   
   Brief description of what this method does.
   
   ### Parameters
   
   | Name | Type | Required | Description |
   |------|------|----------|-------------|
   | param1 | string | Yes | Description |
   | param2 | int | No | Description (default: 0) |
   
   ### Returns
   
   `ReturnType` - Description of the return value
   
   ### Throws
   
   - `ExceptionType` - When this exception is thrown
   
   ### Example
   
   ```language
   // Example usage
   const result = methodName("hello", 42);

3. **Output Format**
- Use project's documentation style if defined in CLAUDE.md
- Include table of contents for large files
- Add code examples for complex methods
- Link related methods/classes

## Constraints

- Don't document private/internal methods unless requested
- Keep descriptions concise but complete
- Use consistent terminology across the documentation

Usage:

/generate-api-docs

4. Debug Helper (/debug)

File: .claude/commands/debug.md

# Debug Assistant

Help diagnose and fix issues in the current code.

## Instructions

### When given an error message:

1. **Parse the Error**
   - Identify error type and message
   - Extract stack trace information
   - Find the root cause location

2. **Analyze Context**
   - Read related code files
   - Check recent changes that might have caused the issue
   - Look for similar patterns in the codebase

3. **Provide Solutions**
   - Explain why the error occurred
   - Offer multiple fix options with trade-offs
   - Include code snippets for each solution
   - Suggest preventive measures

### When asked to debug generally:

1. **Code Review**
   - Check for common bugs (null pointers, off-by-one, race conditions)
   - Verify edge case handling
   - Review error handling completeness

2. **Add Debug Points**
   - Suggest logging statements to add
   - Recommend breakpoint locations
   - Propose test cases to isolate the issue

## Output Format

```markdown
## Issue Analysis

**Error**: [Error message]
**Location**: [File:line]
**Root Cause**: [Explanation]

## Solutions

### Option 1: [Name] (Recommended)
[Explanation]
```code
// Fix code

Option 2: [Name]

[Explanation]

// Alternative fix

Prevention

  • [How to prevent this in the future]

5. Test Generator (/test)

File: .claude/commands/test.md

# Generate Tests

Create comprehensive test cases for the current file or function.

## Instructions

1. **Analyze the Code**
   - Identify all public methods/functions
   - Map out dependencies and side effects
   - Find edge cases and boundary conditions

2. **Generate Test Cases**

   For each method, create tests for:
   
   - **Happy Path**: Normal expected usage
   - **Edge Cases**: Boundary values, empty inputs, max values
   - **Error Cases**: Invalid inputs, exceptions, failures
   - **Integration**: Interactions with other components

3. **Test Structure**

   Use the project's testing framework. Default to:
   

describe('ClassName/ModuleName', () => { describe('methodName', () => { it('should [expected behavior] when [condition]', () => { // Arrange // Act // Assert }); }); });


4. **Best Practices**
- One assertion per test when possible
- Use meaningful test descriptions
- Mock external dependencies
- Keep tests independent and isolated

## Output

- Complete test file ready to save
- Coverage analysis of what's tested
- Suggestions for additional edge cases to consider

Create Your Own Slash Commands

Basic Structure

# Command Name

Brief description of what this command does.

## Instructions

1. Step-by-step instructions for Claude
2. Include specific rules and constraints
3. Define expected output format

## Context (Optional)

Additional context Claude should consider.

## Output Format

Define how the output should be structured.

## Constraints

- List any limitations or rules
- Define what NOT to do

Best Practices

  1. Be clear and specific: Describe exactly what you want
  2. Structured output: Define output format clearly
  3. Constraints: Set limits to avoid unwanted results
  4. Examples: Add examples if needed
  5. Context-aware: Reference project conventions in CLAUDE.md

Example: Custom Slash Command for Laravel

File: .claude/commands/laravel-controller.md

# Generate Laravel Controller

Create a new Laravel controller following project conventions.

## Instructions

1. **Check CLAUDE.md** for project-specific conventions
2. **Generate Controller** with:
   - Type hints for all parameters and return types
   - Form Request validation classes
   - Resource responses for APIs
   - Proper error handling

3. **Follow Laravel conventions**:
   - RESTful method naming (index, show, store, update, destroy)
   - Single responsibility per method
   - Use dependency injection
   - Use Laravel Pint formatting

## Template

```php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\{Resource}StoreRequest;
use App\Http\Requests\{Resource}UpdateRequest;
use App\Http\Resources\{Resource}Resource;
use App\Models\{Resource};
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

final class {Resource}Controller extends Controller
{
    public function index(): AnonymousResourceCollection
    {
        // Implementation
    }
    
    public function store({Resource}StoreRequest $request): JsonResponse
    {
        // Implementation
    }
    
    // ... other methods
}

Output

  • Controller file
  • Form Request files (if needed)
  • Resource file (if API)
  • Route suggestions

## Advanced Slash Commands

### Using Variables

You can pass arguments to slash commands:

/optimize --file=src/services/UserService.php --focus=performance


In the Markdown file, reference variables:

```markdown
# Optimize Code

Analyze {{file}} with focus on {{focus}}.

...

Chaining with Memory

Slash commands can reference project memory:

# Code Review

Review code following standards defined in CLAUDE.md.

## Instructions

1. Load project conventions from CLAUDE.md
2. Apply team-specific rules
3. Check against coding standards

Combining with Subagents

# Full Code Review

Perform comprehensive code review using specialized agents.

## Instructions

1. Delegate security review to @secure-reviewer
2. Delegate performance review to @performance-expert
3. Delegate test coverage to @test-engineer
4. Synthesize all findings

Troubleshooting

Command not recognized

  1. Check file has .md extension
  2. Check location: .claude/commands/ or ~/.claude/commands/
  3. Restart Claude Code session

Output not as expected

  1. Add more details to Instructions
  2. Define output format more clearly
  3. Add examples for Claude to reference
  4. Use constraints to eliminate unwanted results

Summary

Slash Commands are an excellent starting point for customizing Claude Code:

  • ✅ Easy to create (just Markdown files)
  • ✅ No complex configuration needed
  • ✅ Reusable
  • ✅ Shareable with team

Next Up

In the next part, we'll explore Memory — how to use CLAUDE.md to define project conventions and context that's automatically loaded in every session.

References


This series is translated and expanded from claude-howto — MIT License.

Comments