05

High-Quality Prompt Templates

⏱️ 12 min

High-Quality Prompt Templates

In day-to-day development, fixed templates let you consistently reproduce good results. Here are 3 patterns you can use right away.

Task + Context + Constraints + Output + Acceptance

[Task] Implement frontend validation logic for a login form
[Context] Using React + TypeScript, existing components Form and Input, can reuse hooks/useToast
[Constraints] Don't add new dependencies; return specific field-level error messages on failure
[Output] Complete code block with type definitions; include 2 input/output examples
[Acceptance] Code must pass ESLint; explain which edge cases are covered

This works for the vast majority of feature work. The key is spelling out "where the project stands now" and "what counts as done."

Role + Steps + Checklist

You're a code review assistant. Follow these steps:
1) Read @pages/login.tsx and @components/Form.tsx
2) Find accessibility issues that can be improved
3) Output a fix as a patch (in a Markdown code block), then list a checklist
Checklist: keyboard navigable, fields have labels, error messages are screen-reader accessible

Good for refactoring, reviews, and accessibility audits — anything that benefits from a structured checklist.

Diff/Patch Instructions

Generate a patch for @components/Button.tsx:
- Change the primary button background to #0f172a, add shadow on hover
- Keep props unchanged, don't break existing usage
- Output a unified diff, don't include unrelated files

When you're making small changes to existing code, asking for a patch minimizes collateral damage and unrelated modifications.

Practice

  • Pick one of the patterns above and run it in Cursor against your current project. See if AI follows the format.
  • Tweak the "constraints" and "acceptance" fields, observe how the output changes, and start building your own template library.

📚 相关资源

❓ 常见问题

关于本章主题最常被搜索的问题,点击展开答案

「任务+背景+约束+输出+验收」5 段式模板适合哪种场景?

适合绝大多数功能开发任务 —— 写新组件、加 form 校验、写 utility、对接 API。关键是把"项目现状"(已有的 Form / Input / hooks)和"验收"(通过 ESLint、覆盖空输入边界)写清楚。这两块缺了,AI 就只能产出泛化代码。模板看似啰嗦,但比"帮我写个登录校验"省 3 轮返工。

「角色 + 步骤 + 检查表」模板特别适合哪类工作?

适合 review、重构、可访问性审查这类需要列表化检查的任务。例:让 AI 当 code reviewer,先读 @pages/login.tsx + @components/Form.tsx,再找可访问性问题,最后输出 patch + 检查表(可键盘操作 / 字段有 label / 错误信息屏幕阅读器可读)。检查表这一段是关键 —— 把验收标准前置,AI 输出会自动对齐。

什么时候应该让 AI 输出 unified diff 而不是完整代码?

已有代码上做小改动时。例:给 @components/Button.tsx 改 primary 配色为 #0f172a + 加 hover 阴影,要求 props 不变。让 AI 出 patch 而不是整个文件,能避免它顺手把无关 import、无关样式、注释都改一遍 —— 那种"全文件改写"经常带来 30+ 行无关 diff,PR 评审最痛。

怎么把好用的 prompt 沉淀成自己的模板库?

三步走:(1) 每次跑出满意结果立刻存到本地文件(prompts/ 目录或 Notion 都行),不要靠记忆;(2) 标注适用场景 —— 这条是给 React 组件用的、那条是 PR review 专用;(3) 用变量占位 ——「[文件名]」「[stack]」「[验收]」之类,下次用直接替换。3 个月后你的模板库就是真正拉开同事差距的资产。

AI 没有按要求的格式(unified diff / 表格 / 检查表)输出怎么办?

直接回一句"重新输出,必须是 unified diff 格式,不要包含无关文件" —— 不要重新解释整个 task。AI 偶尔会忽略格式约束,特别是上下文长的时候。第二次重复格式要求几乎都能拿到合规输出。如果连续 2 次还不行,把格式约束移到 prompt 最末尾(last instruction wins),通常立刻见效。