第 7 章

.cursorrules 工程化——4套生产可用模板,让 AI 真正懂你的项目

第7章:.cursorrules 工程化——4套生产可用模板,让 AI 真正懂你的项目

.cursorrules 是写给 AI 的项目说明书——告诉它你用什么技术栈、遵循什么规范、有哪些禁忌。没有它,AI 每次生成代码都在猜你的偏好;有了它,AI 生成的代码天然符合项目风格。本章给出4套直接可用的生产模板,覆盖主流全栈场景。

.cursorrules 文件的作用机制

每次你打开 Cursor Chat 或 Composer,.cursorrules 的内容会被自动注入到 AI 的系统提示里。它相当于每次对话开始前,AI 都先读了一遍你的项目规范。

效果:

模板一:React + TypeScript 全栈项目

# Tech Stack
- Frontend: React 18, TypeScript strict mode, Tailwind CSS v3
- Backend: Next.js 14 App Router, Server Actions
- Database: PostgreSQL + Prisma ORM
- Auth: NextAuth.js v5

# Code Style
- 2-space indent, single quotes, no semicolons (Prettier defaults)
- No `any` type — use `unknown` and narrow it explicitly
- Functional components only, no class components
- Custom hooks must start with `use`, placed in /src/hooks/
- All async functions must handle errors (try/catch or .catch())

# File Structure
/src/app/          → Next.js pages and layouts (App Router)
/src/components/   → React components
  /ui/             → Generic UI primitives (Button, Input, Modal)
  /features/       → Domain-specific components (UserProfile, OrderList)
/src/hooks/        → Custom React hooks
/src/lib/          → Utilities and third-party clients
/src/server/       → Server-only code (DB queries, auth helpers)

# API Conventions
- All API responses: { data: T | null, error: string | null }
- HTTP status codes: 200 ok, 201 created, 400 bad request, 401 unauthorized, 404 not found, 500 server error
- Never expose stack traces in API responses

# Forbidden
- No `useEffect` for data fetching — use React Query or Server Components
- No direct database queries in Client Components
- No hardcoded API keys or secrets in source code

模板二:FastAPI + Python 后端

# Tech Stack
- Python 3.12, FastAPI, SQLAlchemy 2.0 (async), Alembic
- Database: PostgreSQL
- Auth: JWT (python-jose), bcrypt for password hashing
- Task Queue: Celery + Redis
- Testing: pytest, pytest-asyncio

# Code Style
- Follow PEP 8, use ruff for formatting
- All functions and methods must have type annotations
- Pydantic models for all request/response schemas — no raw dicts in API layer
- SQLAlchemy models in /app/models/, Pydantic schemas in /app/schemas/

# Error Handling
- Raise HTTPException with proper status codes in route handlers
- Service layer raises custom exceptions (defined in /app/exceptions.py)
- Never let raw SQLAlchemy exceptions bubble up to the API layer
- Log all 5xx errors with structlog

# Security
- All passwords hashed with bcrypt (min cost factor 12)
- JWT secrets from environment variables only
- SQL: always use parameterized queries or ORM — never string concatenation
- Validate all user input with Pydantic before use

# Directory Structure
/app/routers/      → API route handlers (thin layer, business logic in services)
/app/services/     → Business logic
/app/repositories/ → Database access layer
/app/models/       → SQLAlchemy ORM models
/app/schemas/      → Pydantic request/response models
/app/core/         → Config, dependencies, security utilities

模板三:Go 微服务

# Tech Stack
- Go 1.22+, standard library preferred
- Web: net/http + chi router
- Database: PostgreSQL, pgx driver, sqlc for type-safe queries
- Config: viper (from environment variables)
- Logging: slog (structured, JSON format in production)
- Testing: stdlib testing + testify

# Code Style
- gofmt + golangci-lint strict
- Error wrapping: always use fmt.Errorf("context: %w", err) — never discard errors
- Function names: CamelCase for exported, camelCase for unexported
- Interfaces: define at point of use, not in the package that implements

# Error Handling
- Return errors to caller — no panic in library code
- Sentinel errors for expected cases (ErrNotFound, ErrUnauthorized)
- Wrap with context at every layer crossing

# Package Layout
/cmd/server/       → main.go, only wiring
/internal/
  /handler/        → HTTP handlers (thin, delegate to service)
  /service/        → Business logic
  /repository/     → Database access
  /domain/         → Domain types and interfaces
/pkg/              → Public reusable packages

# Forbidden
- No global state except logger and metrics
- No init() functions that have side effects
- No ORM — use sqlc generated code for type safety

模板四:Node.js + Prisma 后端

# Tech Stack
- Node.js 20 LTS, TypeScript strict
- Framework: Express 4.x
- ORM: Prisma 5
- Auth: JWT (jsonwebtoken), bcrypt
- Validation: zod
- Testing: Jest + Supertest

# Code Style
- 2-space indent, single quotes, semicolons required
- All route handlers must be async
- Zod schema validation on all request bodies before processing
- Error-first middleware pattern: (err, req, res, next)

# Project Structure
/src/routes/       → Express route definitions
/src/controllers/  → Request/response handling (thin)
/src/services/     → Business logic
/src/repositories/ → Prisma DB access
/src/middleware/   → Auth, error handling, logging
/src/lib/          → Utility functions
/src/types/        → Shared TypeScript types

# Database
- Use Prisma transactions for multi-step writes
- Always select only needed fields — avoid select *
- Use cursor-based pagination for large datasets

# Security
- JWT secrets from process.env only
- No raw SQL string concatenation — use Prisma or parameterized queries
- Rate limiting on all public endpoints
- Sanitize all user input before logging (mask PII)

如何验证 .cursorrules 是否生效

写好 .cursorrules 后,用这两个方法验证:

方法1:在 Chat 里问 AI

你了解这个项目的技术栈和代码规范吗?请描述一下主要约定。

如果 AI 能准确描述你在 .cursorrules 里写的内容,说明它已经被正确读取。

方法2:生成一个测试文件

帮我创建一个用于测试的 UserService,包含 getUserById 和 updateUser 两个方法,
按照项目规范写,不要添加任何注释解释说明。

检查生成的代码:命名风格、错误处理、导入方式是否都符合你的规范。

常见诊断问题

问题 可能原因 解决方法
AI 生成的代码风格和规范不符 .cursorrules 没有被读取 检查文件是否在项目根目录,文件名拼写是否正确
AI 不遵守某条规则 规则描述太模糊 把"应该用 XXX"改成"必须用 XXX,禁止用 YYY"
每次生成风格不一致 .cursorrules 缺少具体约束 加入真实的代码示例,比"描述规则"更有效
AI 引入了不在 package.json 的依赖 没有明确禁止 在 Forbidden 章节列出不允许引入新依赖

域知识注入

.cursorrules 不只是代码规范,还可以注入业务领域知识:

# Domain Knowledge
- "用户" 在我们的系统里指 B 端客户(企业),不是 C 端消费者
- "订单状态流转":draft → pending → paid → shipped → delivered / cancelled
- 所有涉及金额的字段,单位是"分"(整数),不是"元"
- userId 在数据库里是 UUID,在 URL 参数里 encode 成 base64url

这类知识如果不写进 .cursorrules,AI 每次都会用通用假设,容易与你的业务逻辑冲突。

本章要点

  1. .cursorrules 是每次对话的前置上下文:写好一次,所有对话都受益,是杠杆最高的一次性投资
  2. 四套模板覆盖主流场景:React+TS、FastAPI、Go 微服务、Node.js+Prisma,直接复制修改即可
  3. 规则要具体,不要模糊:"必须用 X,禁止用 Y"比"应该用 X"有效十倍
  4. Forbidden 章节是防线:明确写出哪些做法是禁止的,防止 AI 走捷径用了你不想要的方案
  5. 域知识和代码规范同样重要:业务术语、状态流转、字段单位,写进去让 AI 理解你的业务上下文
本章评分
4.6  / 5  (45 评分)

💬 留言讨论