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 featureCommand 分类
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-migration | Supabase 迁移助手 |
/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 scenariosSecurity 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 stepsSmart 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 logicUpdate 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"最佳实践
- 命名清晰:使用动词开头的命名,如
generate-,update-,run- - 单一职责:每个命令专注一个任务
- 文档完善:在命令中包含清晰的使用说明
- 错误处理:考虑各种边界情况
- 状态检测:使用
!语法检测当前环境状态
下一步
- 6.3 Settings & Hooks - 配置与自动化
- 6.4 MCPs 集成 - 外部服务连接