Cursor 进阶:Rules、Composer 与自定义配置
深入 Cursor 的 .cursorrules、Composer 多文件编辑、自定义模型配置
为什么需要进阶
如果你已经用过 Cursor 的基础功能——Tab 补全、Chat 对话、简单的 Inline Edit——你可能会觉得”也就那样”。但 Cursor 真正的威力藏在它的进阶功能里:.cursorrules 让 AI 理解你的项目规范,Composer 让多文件编辑变得丝滑,自定义模型配置让你用上最适合的 AI 模型。
这篇文章我们深入这些进阶功能,帮你把 Cursor 从”能用”变成”好用”。
.cursorrules 详解
什么是 .cursorrules
.cursorrules 是 Cursor 的项目级配置文件,放在项目根目录下。它告诉 Cursor 的 AI 关于你项目的一切:技术栈、编码规范、架构约定、甚至你的个人偏好。
可以把它理解为给 AI 写的一份”项目须知”。有了它,AI 生成的代码会更贴合你的项目风格。
基本格式
.cursorrules 使用 Markdown 格式,结构清晰即可:
# Project: My Awesome App
## Tech Stack
- Framework: Next.js 14 (App Router)
- Language: TypeScript 5.x (strict mode)
- Styling: Tailwind CSS + shadcn/ui
- Database: PostgreSQL with Prisma ORM
- Testing: Vitest + React Testing Library
- State Management: Zustand
## Code Style
- Use functional components with hooks
- Prefer named exports over default exports
- Use absolute imports with @/ prefix
- Keep components under 150 lines
- Extract business logic into custom hooks
## Naming Conventions
- Components: PascalCase (UserProfile.tsx)
- Hooks: camelCase with use prefix (useAuth.ts)
- Utils: camelCase (formatDate.ts)
- Types: PascalCase with suffix (UserDTO, CreateUserInput)
- API routes: kebab-case folders
## File Structure
src/ app/ # Next.js App Router pages components/ # Reusable UI components hooks/ # Custom React hooks lib/ # Utility functions and configs services/ # API service layer types/ # TypeScript type definitions
## Error Handling
- Use custom AppError class for business errors
- Always wrap async operations in try-catch
- Return structured error responses from API routes
- Log errors with sufficient context
## Testing
- Write unit tests for all utility functions
- Write integration tests for API routes
- Use MSW for mocking API calls in tests
- Minimum 80% code coverage
高级技巧
1. 提供代码示例
在 .cursorrules 中直接给出代码示例,AI 会模仿这个风格:
## API Route Example
Follow this pattern for all API routes:
```typescript
// src/app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { prisma } from '@/lib/prisma';
import { handleApiError } from '@/lib/errors';
const createUserSchema = z.object({
name: z.string().min(2).max(50),
email: z.string().email(),
});
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const data = createUserSchema.parse(body);
const user = await prisma.user.create({ data });
return NextResponse.json(user, { status: 201 });
} catch (error) {
return handleApiError(error);
}
}
#### 2. 定义禁止事项
明确告诉 AI 什么不该做:
```markdown
## Do NOT
- Do not use `any` type in TypeScript
- Do not use class components
- Do not use CSS modules (use Tailwind instead)
- Do not use relative imports for cross-directory references
- Do not put business logic in components
- Do not use console.log in production code (use logger)
3. 分场景配置
针对不同类型的任务给出不同的指导:
## When Writing Components
- Always add proper TypeScript props interface
- Include loading and error states
- Make components accessible (aria labels, keyboard nav)
- Add JSDoc comments for complex props
## When Writing Tests
- Use describe/it pattern
- Test happy path first, then edge cases
- Mock external dependencies
- Use meaningful test descriptions
## When Refactoring
- Preserve existing functionality
- Add tests before refactoring if missing
- Make small, incremental changes
- Update related documentation
.cursorrules 最佳实践
- 保持文件在 500 行以内,太长 AI 可能忽略部分内容
- 把最重要的规则放在前面
- 使用清晰的 Markdown 标题分组
- 定期更新,随项目演进调整
- 团队共享,提交到版本控制
Composer 多文件编辑
Composer 是什么
Composer 是 Cursor 的多文件编辑功能,按 Cmd + I 打开。它和 Chat 的区别在于:Chat 主要用于讨论和理解代码,Composer 则专注于跨文件的代码生成和修改。
基本用法
打开 Composer 后,描述你想要完成的任务:
创建一个完整的用户认证模块:
1. src/lib/auth.ts - JWT 工具函数(生成、验证、刷新)
2. src/middleware.ts - Next.js 中间件,保护需要认证的路由
3. src/app/api/auth/login/route.ts - 登录接口
4. src/app/api/auth/register/route.ts - 注册接口
5. src/hooks/useAuth.ts - 前端认证 hook
Composer 会依次生成这些文件,每个文件都会展示完整的代码和 diff。
高级用法
引用已有文件
在 Composer 中使用 @ 引用已有文件作为上下文:
@file:src/types/user.ts
@file:src/lib/prisma.ts
基于已有的 User 类型和 Prisma 配置,
创建用户 CRUD 的 API 路由和 Service 层
引用代码库
使用 @codebase 让 Composer 搜索整个项目:
@codebase
参考项目中已有的 API 路由模式,
为 Product 模型创建完整的 CRUD 接口
引用文档
使用 @doc 引用外部文档:
@doc:https://nextjs.org/docs/app/api-reference/functions/next-response
使用 Next.js 最新的 NextResponse API 重写我们的 API 路由
Composer 工作流技巧
1. 分步骤执行
不要一次给 Composer 太多任务。分步骤执行效果更好:
# 第一步
创建数据模型和类型定义
# 第二步
创建 Service 层
# 第三步
创建 API 路由
# 第四步
创建前端组件和 hooks
2. 审查和调整
Composer 生成代码后,不要急着全部接受。逐个文件审查:
- 点击文件名查看完整代码
- 使用 diff 视图检查修改
- 对不满意的部分,在 Composer 中继续对话调整
- 接受满意的文件,拒绝需要修改的文件
3. 结合 Chat 使用
先用 Chat 讨论方案,确定后再用 Composer 执行:
# 在 Chat 中
"我想给项目添加 WebSocket 实时通知功能,
你觉得应该怎么设计架构?"
# AI 给出方案后,在 Composer 中
"按照刚才讨论的方案,开始实现 WebSocket 通知功能"
自定义模型配置
切换模型
Cursor 支持多种 AI 模型,在设置中可以配置:
Settings > Models > Model Selection
可选模型包括:
| 模型 | 特点 | 适用场景 |
|---|---|---|
| Claude Sonnet | 平衡速度和质量 | 日常开发 |
| Claude Opus | 最强推理能力 | 复杂架构设计 |
| GPT-4o | 速度快 | 快速迭代 |
| GPT-4o mini | 最快 | 简单补全 |
使用自己的 API Key
如果你有自己的 API Key,可以在设置中配置:
Settings > Models > API Keys
配置后可以不受 Cursor 免费额度限制,按实际使用量付费。
针对不同任务选择模型
一个实用的策略是针对不同任务使用不同模型:
- Tab 补全:使用快速模型(GPT-4o mini)
- Chat 对话:使用平衡模型(Claude Sonnet)
- Composer 多文件编辑:使用强力模型(Claude Opus)
代码库索引
开启索引
Cursor 的代码库索引功能让 AI 能理解整个项目:
Settings > Features > Codebase Indexing > Enable
索引完成后,你可以在 Chat 中使用 @codebase 搜索整个项目。
索引配置
通过 .cursorignore 文件排除不需要索引的内容:
# .cursorignore
node_modules/
dist/
build/
.next/
coverage/
*.min.js
*.map
package-lock.json
索引的好处
开启索引后,AI 的表现会显著提升:
- 理解项目的整体架构
- 找到相关的类型定义和接口
- 遵循项目中已有的代码模式
- 正确引用其他模块的导出
@-mentions 系统
Cursor 的 @ 引用系统非常强大,我们来详细了解:
可用的 @ 引用
| 引用 | 说明 | 示例 |
|---|---|---|
@file | 引用特定文件 | @file:src/utils.ts |
@folder | 引用文件夹 | @folder:src/components |
@codebase | 搜索代码库 | @codebase 认证相关代码 |
@web | 搜索网络 | @web React 19 新特性 |
@doc | 引用文档 | @doc:https://... |
@git | 引用 Git 信息 | @git 最近的提交 |
@definitions | 引用符号定义 | @definitions UserService |
组合使用
多个 @ 引用可以组合使用:
@file:src/types/order.ts
@file:src/services/order.ts
@codebase 支付相关
基于已有的 Order 类型和 Service,
添加支付功能,参考项目中已有的支付相关代码
键盘快捷键速查
| 快捷键 | 功能 |
|---|---|
Tab | 接受补全 |
Cmd + K | Inline Edit |
Cmd + L | 打开 Chat |
Cmd + I | 打开 Composer |
Cmd + Shift + L | 将选中代码添加到 Chat |
Cmd + Shift + K | 将选中代码添加到 Inline Edit |
Cmd + Enter | 在 Chat 中发送(带 codebase 搜索) |
Esc | 拒绝补全建议 |
Alt + ] / Alt + [ | 切换补全建议 |
实用技巧合集
1. 快速生成类型
选中 JSON 数据,按 Cmd + K,输入:
将这个 JSON 转换为 TypeScript interface
2. 批量重命名
在 Chat 中:
@codebase
将所有使用 fetchData 的地方改为 queryData,
包括函数定义、调用和导入
3. 生成 API 文档
@folder:src/app/api
为所有 API 路由生成 OpenAPI 3.0 规范文档
4. 代码审查
@git 最近 5 次提交的改动
审查这些改动,找出潜在的问题和改进点
5. 调试辅助
将错误信息粘贴到 Chat 中:
运行时出现这个错误:
TypeError: Cannot read properties of undefined (reading 'map')
at UserList (src/components/UserList.tsx:15:23)
@file:src/components/UserList.tsx
帮我找出原因并修复
从基础到进阶的路径
如果你刚开始使用 Cursor,建议按这个顺序逐步掌握:
- 先熟悉 Tab 补全,养成接受/拒绝建议的习惯
- 学会使用
Cmd + K进行 Inline Edit - 开始使用 Chat 讨论代码问题
- 创建
.cursorrules文件,定义项目规范 - 开启代码库索引,使用
@codebase搜索 - 掌握 Composer 进行多文件编辑
- 根据需要配置自定义模型
每一步都建立在前一步的基础上,不要急于求成。
工具的进阶不在于功能的堆叠,而在于找到最适合你工作流的那几个核心功能,然后把它们用到极致。
相关文章
评论
加载中...
评论
加载中...