第06章 写自己的 Skill:把重复提示词变成工程资产

当你第三次把同一段提示词复制给 Claude Code,就该考虑把它写成 skill。

Skill 的本质是:把可复用的上下文、步骤、检查清单和工具约束放进一个目录,让 Claude Code 在需要时自动加载,或者由你用 /skill-name 主动调用。

最小结构

个人级 skill 放在:

~/.claude/skills/<skill-name>/SKILL.md

项目级 skill 放在:

.claude/skills/<skill-name>/SKILL.md

最小文件如下:

---
description: Review the current diff and produce a concise risk list before commit.
---

Review the current git diff.

Focus on:
- correctness bugs
- missing tests
- accidental behavior changes
- unrelated edits

Do not modify files.

目录名会成为命令名。例如目录是 precommit-review,就可以运行:

/precommit-review

description 决定自动触发质量

description 不是装饰字段。Claude Code 会用它判断什么时候该自动加载这个 skill。

差的写法:

description: Useful development helper.

好的写法:

description: Review uncommitted git changes before commit. Use when the user asks for a pre-commit check, commit readiness, risk review, or diff review.

写 description 的原则:

  • 第一短句说清楚 skill 做什么。
  • 后面补充触发场景。
  • 不要写抽象价值观。
  • 不要塞入长篇教程。

什么时候禁止自动触发

有副作用的 skill 应该加:

disable-model-invocation: true

例如部署、发消息、创建 PR、删除缓存、改数据库。这类 skill 只能由用户手动调用,避免 Claude 判断“差不多可以部署了”就自动执行。

示例:

---
description: Deploy the current branch to staging after tests pass.
disable-model-invocation: true
---

Deploy to staging:
1. Confirm current branch and diff.
2. Run the full test suite.
3. Build the artifact.
4. Run the staging deploy command.
5. Verify the deployment endpoint.

用 supporting files 控制上下文成本

不要把所有知识都塞进 SKILL.md。官方建议把详细资料拆到支持文件里,只在需要时读取。

推荐结构:

my-skill/
├── SKILL.md
├── reference.md
├── examples.md
└── scripts/
    └── validate.sh

SKILL.md 保持短,只负责导航:

## Additional resources

- For API details, read reference.md when needed.
- For expected output examples, read examples.md when formatting the final answer.
- For validation, run scripts/validate.sh after edits.

这样既保留能力,又避免每次调用都把大段资料塞进上下文。

可以把命令输出注入到 skill

Skill 支持动态上下文注入。例如:

## Current diff

!`git diff HEAD`

## Instructions

Summarize the change and list risks.

Claude Code 会在读取 skill 前执行命令,把输出注入上下文。

这很强,但也要克制使用:

  • 只注入必要信息。
  • 避免注入巨大日志。
  • 不要在自动触发 skill 中注入高风险命令。

三类最值得写的项目级 skill

第一类是验证 skill:

.claude/skills/verify-api/
.claude/skills/verify-frontend/
.claude/skills/verify-docs/

它们记录项目真实验证路径,比一句“运行测试”可靠。

第二类是发布 skill:

.claude/skills/release-checklist/
.claude/skills/publish-docs/

这类 skill 要禁用自动触发,只能手动调用。

第三类是风格与架构 skill:

.claude/skills/api-conventions/
.claude/skills/frontend-patterns/

它们适合自动触发,帮助 Claude Code 在写代码时遵守项目惯例。

判断一个 skill 是否值得保留

保留标准很简单:

  • 它是否减少了重复解释?
  • 它是否让输出更稳定?
  • 它是否记录了项目真实流程?
  • 它是否比 CLAUDE.md 中的一段说明更适合“被调用”?

如果只是事实,放 CLAUDE.md。如果是步骤、检查清单、模板、验证流程,写成 skill。

本章小结

Skill 是 Claude Code 里最容易被低估的能力。它不是提示词收藏夹,而是项目工作流的可执行文档。

成熟团队可以把这三件事固化下来:

  1. 项目怎么验证。
  2. 项目怎么发布。
  3. 项目有哪些不可违反的架构约束。

当这些内容变成 skills,Claude Code 才真正拥有“团队经验”。

参考资料:


相关内容

如果这篇文章对你有帮助,欢迎请我喝杯咖啡 ☕
Cygnus Yang 支付宝支付宝
Cygnus Yang 微信微信