Làm chủ Claude Code trong một tuần (Phần 2): Slash Commands

· 9 min read

Đây là phần thứ hai trong series "Làm chủ Claude Code trong một tuần". Trong bài này, chúng ta sẽ tìm hiểu Slash Commands — tính năng cho phép bạn tạo các lệnh tùy chỉnh để tăng tốc workflow.

Slash Commands là gì?

Slash Commands là user-invoked shortcuts được lưu dưới dạng Markdown files. Khi bạn gõ /tên-lệnh trong Claude Code, nó sẽ đọc file Markdown tương ứng và thực thi instructions bên trong.

┌─────────────────────────────────────────────────────────┐
│                    SLASH COMMANDS                        │
├─────────────────────────────────────────────────────────┤
│                                                          │
│   User gõ:  /optimize                                   │
│                    │                                    │
│                    ▼                                    │
│   ┌────────────────────────────────┐                   │
│   │ .claude/commands/optimize.md   │                   │
│   │ ────────────────────────────── │                   │
│   │ # Optimize Code                │                   │
│   │                                │                   │
│   │ Analyze the current file for:  │                   │
│   │ - Performance issues           │                   │
│   │ - Code smells                  │                   │
│   │ - Optimization opportunities   │                   │
│   └────────────────────────────────┘                   │
│                    │                                    │
│                    ▼                                    │
│   Claude thực thi instructions trong file              │
│                                                          │
└─────────────────────────────────────────────────────────┘

Đặc điểm chính

Tiêu chí Giá trị
Cách gọi Manual (/tên-lệnh)
Persistence Session only
Vị trí file .claude/commands/ hoặc ~/.claude/commands/
Format Markdown (.md)
Dùng cho Quick shortcuts, repetitive tasks

Cài đặt

Vị trí lưu trữ

Project-level (chỉ cho dự án hiện tại):

mkdir -p .claude/commands

Global (cho tất cả dự án):

mkdir -p ~/.claude/commands

Copy từ claude-howto

# Clone repo nếu chưa có
git clone https://github.com/luongnv89/claude-howto.git

# Copy tất cả slash commands
cp claude-howto/01-slash-commands/*.md .claude/commands/

Ví dụ 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

Sử dụng:

/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

**Sử dụng**:

/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

Sử dụng:

/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

Tạo Slash Command của riêng bạn

Cấu trúc cơ bản

# 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. Rõ ràng và cụ thể: Mô tả chính xác những gì bạn muốn
  2. Structured output: Định nghĩa format output rõ ràng
  3. Constraints: Đặt giới hạn để tránh kết quả không mong muốn
  4. Examples: Thêm ví dụ nếu cần thiết
  5. Context-aware: Tham chiếu đến project conventions trong CLAUDE.md

Ví dụ: Custom Slash Command cho 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 cho tất cả parameters và return types
   - Form Request validation classes
   - Resource responses cho 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

## Slash Commands nâng cao

### Sử dụng Variables

Bạn có thể truyền arguments vào slash commands:

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


Trong file Markdown, reference variables:

```markdown
# Optimize Code

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

...

Chaining với Memory

Slash commands có thể tham chiếu đến 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

Kết hợp với 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 không được nhận diện

  1. Kiểm tra file có phần mở rộng .md
  2. Kiểm tra vị trí: .claude/commands/ hoặc ~/.claude/commands/
  3. Restart Claude Code session

Output không như mong đợi

  1. Thêm nhiều chi tiết vào Instructions
  2. Định nghĩa output format rõ ràng hơn
  3. Thêm examples cho Claude tham khảo
  4. Sử dụng constraints để loại bỏ kết quả không mong muốn

Tổng kết

Slash Commands là điểm khởi đầu tuyệt vời để tùy chỉnh Claude Code:

  • ✅ Dễ tạo (chỉ cần Markdown file)
  • ✅ Không cần cấu hình phức tạp
  • ✅ Tái sử dụng được
  • ✅ Chia sẻ được với team

Tiếp theo

Trong phần tiếp theo, chúng ta sẽ tìm hiểu Memory — cách sử dụng CLAUDE.md để định nghĩa project conventions và context được tự động load trong mọi session.

Tài liệu tham khảo


Series này được dịch và mở rộng từ claude-howto — MIT License.

Bình luận