Skip to content

6.2 Commands 自定义命令

什么是 Commands?

Commands(命令)是 Claude Code 的斜杠命令扩展。每个 Command 都是一个预定义的工作流模板,可以通过 /command-name 的方式快速调用,实现常见开发任务的自动化。

Command 文件结构

每个 Command 都是一个 Markdown 文件,包含以下部分:

markdown
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [file-path] | [options]
description: 命令的简短描述
---

# 命令标题

命令执行内容: $ARGUMENTS

## Current State(当前状态)
- 状态检测: !`shell command`
- 文件引用: @file-path

## Task(任务)
具体任务描述...

## Process(流程)
1. 步骤1
2. 步骤2

语法说明

语法作用示例
$ARGUMENTS用户传入的参数/generate-tests src/utils.ts
!command执行 shell 命令!git status
@path引用文件内容@package.json

安装 Commands

bash
# 安装单个命令
npx claude-code-templates@latest --command testing/generate-tests --yes

# 安装多个命令
npx claude-code-templates@latest \
  --command testing/generate-tests \
  --command security/security-audit \
  --command git-workflow/commit \
  --yes

# 交互式选择
npx claude-code-templates@latest

安装后,命令会被写入 .claude/commands/ 目录:

.claude/
└── commands/
    ├── generate-tests.md
    ├── security-audit.md
    └── commit.md

使用命令

安装后,在 Claude Code 中直接输入斜杠命令即可使用:

/generate-tests src/components/Button.tsx
/security-audit --full
/commit feat: add new feature

Command 分类

Claude Code Templates 包含 216+ 个预置命令,按功能分类:

1. 测试 (testing)

命令描述
/generate-tests生成全面的测试套件
/run-tests运行测试并分析结果
/test-coverage生成测试覆盖率报告

2. 安全 (security)

命令描述
/security-audit执行全面的安全评估
/dependency-check检查依赖漏洞
/secrets-scan扫描敏感信息泄露

3. Git 工作流 (git-workflow)

命令描述
/commit智能提交,自动生成消息
/pr-create创建 Pull Request
/changelog生成变更日志

4. 性能 (performance)

命令描述
/optimize-bundle优化打包配置
/performance-audit性能审计分析
/add-caching添加缓存策略

5. 文档 (documentation)

命令描述
/update-docs更新项目文档
/generate-api-docs生成 API 文档
/migration-guide创建迁移指南

6. 数据库 (database)

命令描述
/supabase-migrationSupabase 迁移助手
/schema-sync同步数据库 Schema
/data-explorer数据探索工具

7. 部署 (deployment)

命令描述
/deploy部署应用
/rollback回滚部署
/health-check健康检查

8. 项目设置 (setup)

命令描述
/setup-ci-cd配置 CI/CD 流水线
/setup-testing配置测试环境
/migrate-typescript迁移到 TypeScript

经典 Command 示例

Generate Tests

markdown
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [file-path] | [component-name]
description: Generate comprehensive test suite with unit,
  integration, and edge case coverage
---

# Generate Tests

Generate comprehensive test suite for: $ARGUMENTS

## Current Testing Setup

- Test framework: @package.json or @jest.config.js
- Existing tests: !`find . -name "*.test.*" | head -5`
- Target file: @$ARGUMENTS

## Task

I'll analyze the target code and create complete test coverage:

1. Unit tests for individual functions and methods
2. Integration tests for component interactions
3. Edge case and error handling tests
4. Mock implementations for external dependencies
5. Test utilities and helpers as needed

## Test Types

### Unit Tests
- Individual function testing
- Component rendering and prop handling
- State management and lifecycle methods

### Integration Tests
- Component interaction testing
- API integration with mocked responses
- End-to-end user workflows

## Testing Best Practices

- Use descriptive test names
- Follow AAA pattern (Arrange, Act, Assert)
- Aim for 80%+ code coverage
- Test both happy path and error scenarios

Security Audit

markdown
---
allowed-tools: Read, Bash, Grep, Glob
argument-hint: [focus-area] | --full
description: Perform comprehensive security assessment
---

# Security Audit

Perform comprehensive security assessment: $ARGUMENTS

## Current Environment

- Dependency scan: !`npm audit --audit-level=moderate`
- Environment files: @.env*
- Recent commits: !`git log --oneline --grep="security" -10`

## Task

Perform systematic security audit:

1. **Dependency Security**
   - Scan dependencies for vulnerabilities
   - Check for outdated packages

2. **Authentication & Authorization**
   - Review authentication mechanisms
   - Check session management

3. **Input Validation**
   - Check user input sanitization
   - Look for SQL injection vulnerabilities

4. **Data Protection**
   - Check encryption implementation
   - Review data handling practices

5. **Secrets Management**
   - Scan for hardcoded secrets
   - Check environment variable security

6. **Reporting**
   - Document findings with severity levels
   - Provide remediation steps

Smart Commit

markdown
---
allowed-tools: Bash(git add:*), Bash(git status:*),
  Bash(git commit:*), Bash(git diff:*)
argument-hint: [message] | --no-verify
description: Create well-formatted commits with
  conventional commit format and emoji
---

# Smart Git Commit

Create well-formatted commit: $ARGUMENTS

## Current Repository State

- Git status: !`git status --porcelain`
- Current branch: !`git branch --show-current`
- Staged changes: !`git diff --cached --stat`
- Recent commits: !`git log --oneline -5`

## What This Command Does

1. Runs pre-commit checks (lint, build)
2. Checks staged files with `git status`
3. If no files staged, auto-stages modified files
4. Analyzes diff to understand changes
5. Creates commit with emoji conventional format

## Conventional Commit Types

- ✨ feat: New feature
- 🐛 fix: Bug fix
- 📝 docs: Documentation
- 💄 style: Formatting/style
- ♻️ refactor: Code refactoring
- ⚡️ perf: Performance improvements
- ✅ test: Tests
- 🔧 chore: Tooling, configuration

## Examples

Good commit messages:
- ✨ feat: add user authentication system
- 🐛 fix: resolve memory leak in rendering
- 📝 docs: update API documentation
- ♻️ refactor: simplify error handling logic

Update Docs

markdown
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [doc-type] | --implementation | --api
description: Systematically update project documentation
---

# Documentation Update

Update project documentation: $ARGUMENTS

## Current Documentation State

- Documentation structure: !`find . -name "*.md" | head -10`
- Specs directory: @specs/
- Recent changes: !`git log --oneline --since="1 week ago" -- "*.md"`

## Documentation Analysis

1. Review current documentation status
2. Analyze implementation and testing results
3. Identify gaps in documentation

## Documentation Updates

1. Update phase implementation document
   - Mark completed tasks with ✅
   - Update percentages
   - Add implementation notes

2. Update implementation status
   - Phase completion percentages
   - Component status
   - Best practices discovered

3. Update specifications
   - Mark completed items
   - Add implementation references

4. Update CLAUDE.md and README.md
   - New best practices
   - Project status
   - Known issues

## Guidelines

- DO NOT CREATE new specification files
- UPDATE existing files
- Maintain consistent style
- Include practical examples

创建自定义命令

你可以创建自己的自定义命令:

bash
# 创建命令目录
mkdir -p .claude/commands

创建 .claude/commands/my-command.md

markdown
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [your-arguments]
description: 你的命令描述
---

# My Custom Command

执行自定义任务: $ARGUMENTS

## Current State
- 状态检测: !`your-shell-command`
- 配置文件: @your-config-file

## Task
描述你的命令要做什么...

## Process
1. 第一步
2. 第二步
3. 第三步

## Output
期望的输出格式...

高级用法

链式命令

可以组合多个命令执行完整工作流:

bash
# 先审计再提交
/security-audit
/commit fix: address security issues

# 先测试再部署
/generate-tests src/
/run-tests
/deploy production

命令参数

命令支持多种参数格式:

bash
# 文件路径
/generate-tests src/components/Button.tsx

# 选项标志
/security-audit --full
/commit --no-verify

# 多参数
/deploy production --force

完整示例:测试驱动开发工作流

bash
#!/bin/bash
# TDD 工作流配置脚本

# 1. 安装测试相关命令
npx claude-code-templates@latest \
  --command testing/generate-tests \
  --command testing/run-tests \
  --command testing/test-coverage \
  --yes

# 2. 安装代码质量命令
npx claude-code-templates@latest \
  --command security/security-audit \
  --command performance/performance-audit \
  --yes

# 3. 安装 Git 工作流命令
npx claude-code-templates@latest \
  --command git-workflow/commit \
  --command git-workflow/pr-create \
  --yes

echo "TDD 工作流配置完成!"
echo ""
echo "使用方式:"
echo "  /generate-tests src/feature.ts  # 生成测试"
echo "  /run-tests                      # 运行测试"
echo "  /test-coverage                  # 查看覆盖率"
echo "  /security-audit                 # 安全审计"
echo "  /commit                         # 智能提交"
echo "  /pr-create                      # 创建 PR"

最佳实践

  1. 命名清晰:使用动词开头的命名,如 generate-, update-, run-
  2. 单一职责:每个命令专注一个任务
  3. 文档完善:在命令中包含清晰的使用说明
  4. 错误处理:考虑各种边界情况
  5. 状态检测:使用 ! 语法检测当前环境状态

下一步

基于 MIT 许可证发布。内容版权归作者所有。