logo
27

Cursor Rules 编写指南

⏱️ 15分钟

Cursor Rules 编写指南

什么是 Cursor Rules?

Cursor Rules 是一种让 AI 更好地理解你项目的方式。通过定义规则文件,你可以告诉 AI:

  • 项目的编码规范
  • 常用的模式和约定
  • 需要避免的错误
  • 特定的技术要求

Required Rule Structure

每个规则文件应该遵循以下结构:

---
description: Clear, one-line description of what the rule enforces
globs: path/to/files/*.ext, other/path/**/*
alwaysApply: boolean
---

-   **Main Points in Bold**
    -   Sub-points with details
    -   Examples and explanations

File References

# Use [filename](mdc:path/to/file) to reference files

[prisma.mdc](mdc:.cursor/rules/prisma.mdc) for rule references
[schema.prisma](mdc:prisma/schema.prisma) for code references

Code Examples

在规则中使用语言特定的代码块:

// ✅ DO: Show good examples
const goodExample = true;

// ❌ DON'T: Show anti-patterns
const badExample = false;

Rule Content Guidelines

  • Start with high-level overview
  • Include specific, actionable requirements
  • Show examples of correct implementation
  • Reference existing code when possible
  • Keep rules DRY by referencing other rules

Rule Maintenance

  • Update rules when new patterns emerge
  • Add examples from actual codebase
  • Remove outdated patterns
  • Cross-reference related rules

Best Practices

  • Use bullet points for clarity
  • Keep descriptions concise
  • Include both DO and DON'T examples
  • Reference actual code over theoretical examples
  • Use consistent formatting across rules

规则文件位置

  • 项目级别: .cursor/rules/ - 项目特定的规则
  • 用户级别: ~/.cursor/rules/ - 跨项目通用规则

示例:TypeScript 规则

---
description: TypeScript coding standards for this project
globs: '**/*.ts, **/*.tsx'
alwaysApply: true
---

-   **Type Safety**

    -   Always use explicit return types for functions
    -   Avoid `any` type, prefer `unknown` for uncertain types
    -   Use strict null checks

-   **Naming Conventions**

    -   Interfaces: PascalCase with `I` prefix (e.g., `IUser`)
    -   Types: PascalCase (e.g., `UserRole`)
    -   Constants: UPPER_SNAKE_CASE

-   **Code Organization**
    -   One component per file
    -   Group imports: external, internal, types
    -   Export from index files

示例:Git Commit 规则

---
description: Git commit message standards
globs: ''
alwaysApply: false
---

-   **Commit Format**: `type(scope): description`

-   **Types**:

    -   ✨ feat: New features
    -   🐛 fix: Bug fixes
    -   📝 docs: Documentation
    -   ♻️ refactor: Code restructuring
    -   ✅ test: Tests

-   **Best Practices**:
    -   Keep commits atomic and focused
    -   Write in imperative mood
    -   Explain why, not just what

下一步

了解 Git Commit 规范与 Emoji 来提升你的代码提交质量。