AI 工具 | | 约 33 分钟 | 12,868 字

Cursor Rules 进阶:打造你的 AI 编程助手

深入掌握 .cursorrules 配置,构建真正懂你代码库的 AI 编程环境

写在前面

在前面的文章中,我们已经介绍了 .cursorrules 的基础用法——如何定义技术栈、编码规范、文件结构。但如果你想真正发挥 Cursor 的全部潜力,仅靠基础配置是不够的。这篇文章我们深入探讨高级技巧:文件匹配规则、上下文感知配置、团队协作、最佳实践,帮助你把 Cursor 打造成真正懂你项目的 AI 编程助手。

基础回顾与进阶方向

.cursorrules 核心要素

在深入高级话题之前,让我们快速回顾 .cursorrules 的核心要素:

# Project: My App

## Tech Stack
- Next.js 14 + TypeScript
- Tailwind CSS
- PostgreSQL + Prisma

## Code Style
- Functional components only
- Use absolute imports with @/
- TypeScript strict mode

## File Structure
src/
  app/
  components/
  lib/
  types/

这些是基础配置,但进阶的关键在于:如何让这些规则更加精准、智能、并且适应复杂的实际场景。

文件匹配与上下文规则

精确控制生效范围

基础的 .cursorrules 会对整个项目生效,但在大型项目中,你可能需要对不同类型的文件设置不同的规则。Cursor 提供了几种方式来实现这一点。

使用文件路径前缀

在规则描述中明确指定适用场景:

## Rules for API Routes (src/app/api/**)
- Follow RESTful conventions
- Use Zod for request validation
- Return consistent response format
- Include proper error handling

## Rules for Components (src/components/**)
- Use functional components with hooks
- Keep components under 200 lines
- Extract complex logic into custom hooks
- Include loading and error states

## Rules for Utils (src/lib/**)
- Pure functions preferred
- Strong TypeScript typing required
- Document complex functions with JSDoc
- Write unit tests

目录级别的规则覆盖

你可以在子目录中放置专门的配置文件:

project/
  .cursorrules           # 主配置
  src/
    components/
      .cursorrules       # 组件特定规则
    api/
      .cursorrules       # API 特定规则

Cursor 会合并这些配置,子目录的规则优先级更高。

上下文感知的条件规则

虽然没有原生的条件语法,但你可以通过巧妙的结构设计实现类似效果。

场景分类法

## When Writing New Features
- Start with types and interfaces
- Follow TDD: write tests first
- Use feature flags for incomplete features
- Add proper TypeScript types

## When Refactoring
- Preserve all existing functionality
- Write regression tests before starting
- Make incremental changes
- Update related tests and docs

## When Debugging
- Add detailed console logs
- Check edge cases first
- Don't modify code without understanding root cause
- Add unit tests to prevent regression

根据文件类型调整

## TypeScript (.ts/.tsx) Files
- Always enable strict mode
- Use interface over type when possible
- Export types separately from implementations

## Test Files (.test.ts/.spec.ts)
- Use describe/it pattern
- Follow AAA: Arrange, Act, Assert
- Mock external dependencies
- Test happy path and edge cases

## Config Files
- Keep configs in separate files
- Use environment variables for secrets
- Document all config options

Command Rules:自定义 AI 命令

创建自定义命令

除了使用 Cursor 内置的 Chat 和 Composer,你可以在 .cursorrules 中定义自定义命令,让 AI 执行特定任务。

## Custom Commands

### /test
Generate unit tests for the selected code:
- Follow existing test patterns in the project
- Cover happy path and edge cases
- Use meaningful test descriptions
- Mock external dependencies

### /refactor
Refactor the selected code:
- Preserve functionality
- Improve readability
- Extract long functions
- Add proper types

### /docs
Generate documentation:
- JSDoc for functions
- README for modules
- API docs for interfaces
- Include usage examples

### /security
Security audit:
- Check for SQL injection
- Validate input data
- Verify authentication/authorization
- Look for hardcoded secrets

命令的实际使用

定义好命令后,使用方式很简单:

  1. 在 Chat 中输入 /test
  2. 选择要测试的代码
  3. Cursor 会自动按照定义的规则生成测试

进阶:组合命令

## Command Workflows

### /feature
Complete feature workflow:
1. Define types and interfaces first
2. Implement business logic in services
3. Create API routes (if needed)
4. Build UI components
5. Write integration tests
6. Update documentation

### /fix-bug
Bug fix workflow:
1. Reproduce the bug with a test
2. Identify root cause
3. Implement fix
4. Verify test passes
5. Check for similar issues

多文件工作流配置

大型重构工作流

当你需要进行跨多个文件的重构时,可以在 .cursorrules 中定义清晰的工作流:

## Large-Scale Refactoring Workflow

### Step 1: Analysis
- Understand current implementation
- Identify all affected files
- Check existing tests
- Document current behavior

### Step 2: Planning
- Break into small, incremental changes
- Order changes to minimize conflicts
- Plan test strategy
- Identify potential risks

### Step 3: Implementation
- Make one change at a time
- Run tests after each change
- Commit after each successful step
- Document any decisions

### Step 4: Verification
- Run full test suite
- Check code coverage
- Review all changed files
- Test in staging environment

多模块项目配置

对于 monorepo 或多模块项目:

## Monorepo Structure

packages/
  shared/      # Shared utilities and types
  backend/     # API server
  web/         # Frontend application
  mobile/     # Mobile app

## Cross-Package Rules
- Use shared types from @project/shared
- Keep packages loosely coupled
- Document package interfaces
- Version packages independently
- Write integration tests for package boundaries

API 开发工作流

## API Development Workflow

### 1. Design First
- Define request/response schemas
- Document API contracts
- Consider error cases
- Plan versioning strategy

### 2. Implementation Order
1. Database models and migrations
2. Service layer (business logic)
3. API route handlers
4. Request validation
5. Error handling

### 3. API Response Format
```typescript
// Always use this format
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
  };
  meta?: {
    page?: number;
    limit?: number;
    total?: number;
  };
}

测试规则深度配置

单元测试配置

## Unit Testing Rules

### Test File Location
- Test files: alongside source files
- Naming: *.test.ts or *.spec.ts
- Example: src/utils/format.ts -> src/utils/format.test.ts

### Test Structure
```typescript
describe('formatCurrency', () => {
  describe('happy path', () => {
    it('formats USD correctly', () => {
      expect(formatCurrency(100, 'USD')).toBe('$100.00');
    });
  });

  describe('edge cases', () => {
    it('handles zero', () => {
      expect(formatCurrency(0, 'USD')).toBe('$0.00');
    });

    it('handles negative numbers', () => {
      expect(formatCurrency(-50, 'USD')).toBe('-$50.00');
    });
  });
});

集成测试配置

## Integration Testing Rules

### API Tests
- Use supertest or similar for HTTP testing
- Test all endpoints
- Include error cases
- Mock external services
- Test authentication/authorization

### Database Tests
- Use test database
- Clean up data after each test
- Use transactions for test isolation
- Seed minimal required data

### E2E Tests
- Use Playwright
- Test critical user flows
- Run against staging environment
- Include visual regression tests

测试覆盖率规则

## Coverage Requirements

### Minimum Coverage
- Overall: 80%
- New code: 90%
- Critical paths: 100%

### Priority Coverage
1. Business logic in services
2. Utility functions
3. API route handlers
4. Edge cases
5. UI interaction logic

团队协作与配置共享

团队配置策略

1. 核心配置 + 项目配置

# .cursorrules

## Team Standards (Do not modify)
<!-- 这部分由团队统一维护 -->
## Tech Stack
- TypeScript 5.x strict
- React 18
- Next.js 14

## Code Quality
- No console.log in production
- Maximum function length: 50 lines
- Maximum component lines: 150

## Project Specific
<!-- 项目特定配置 -->

2. 分层配置

project/
  .cursorrules              # 项目配置
  .cursorrules.local        # 本地覆盖(不提交)
  docs/
    coding-standards.md     # 详细规范文档

3. 配置模板

创建团队模板,新项目直接复用:

# .cursorrules Template

## Project Info
- Project name: [PROJECT_NAME]
- Description: [DESCRIPTION]
- Tech stack: [STACK]

## Team Rules
- Code review required for all PRs
- Run tests before commit
- Use conventional commits

## Tech Stack
- Language: [LANGUAGE]
- Framework: [FRAMEWORK]
- Testing: [TESTING]

## Code Style
- [TEAM_RULES]

## Architecture
[PROJECT_STRUCTURE]

代码审查规则集成

## Code Review Checklist

### Before Submitting PR
- [ ] All tests pass
- [ ] Code follows style guide
- [ ] No console.log or debugger
- [ ] Types are complete
- [ ] Documentation updated
- [ ] No sensitive data in code

### Review Points
- Error handling complete
- Performance considered
- Security reviewed
- Accessibility checked
- Mobile responsive (if UI)

最佳实践与避坑指南

配置最佳实践

1. 保持简洁

# Good: 简洁明了
## Code Style
- Functional components
- TypeScript strict
- Named exports

# Bad: 过于冗长
## Code Style
- We prefer to use functional components rather than class components
- TypeScript should always be in strict mode
- Always prefer named exports instead of default exports when possible

2. 使用具体示例

## API Response Format

Follow this exact pattern:
```typescript
// src/app/api/users/route.ts
export async function GET() {
  const users = await db.user.findMany();
  return Response.json({ data: users });
}

3. 明确优先级

## Most Important (Must Follow)
- Never use any type
- Always validate user input
- Handle all errors

## Important (Try to Follow)
- Keep functions under 50 lines
- Write tests for new features

## Nice to Have
- Add comments for complex logic
- Keep components small

常见错误与避免方法

错误一:规则太多

# Bad: 200+ 行规则
## 100+ 条详细规则...

# Good: 精选 10-15 条核心规则
## Most Important Rules
- TypeScript strict
- Functional components
- Error handling
- Input validation

错误二:规则太模糊

# Bad: 模糊不清
## Code Quality
- Write good code
- Be careful with errors
- Make it efficient

# Good: 具体可执行
## Code Quality
- Always use try-catch for async operations
- Validate all API inputs with Zod
- Use useMemo for expensive computations

错误三:从不更新

建议每个季度 review 一次 .cursorrules

## Review Checklist
- [ ] Tech stack up to date?
- [ ] Still following current patterns?
- [ ] Any new conventions to add?
- [ ] Remove outdated rules?
- [ ] Team feedback incorporated?

错误四:规则互相矛盾

# Bad: 矛盾规则
## Code Style
- Use default exports for components
- Prefer named exports

# Good: 明确偏好
## Code Style
- Prefer named exports
- Exception: barrel files (index.ts) can use default

进阶配置示例

Next.js 全栈项目配置

# Full-Stack Next.js Project

## Tech Stack
- Next.js 14 (App Router)
- TypeScript 5.x strict
- Prisma ORM + PostgreSQL
- Tailwind CSS + shadcn/ui
- Vitest + Testing Library
- Zustand for state

## Project Structure

src/ app/ # Next.js App Router components/ # React components ui/ # Base UI components features/ # Feature-specific components lib/ # Utilities services/ # Business logic types/ # TypeScript types hooks/ # Custom hooks stores/ # Zustand stores


## API Routes

### Request Validation
```typescript
// Always use Zod schemas
const createUserSchema = z.object({
  name: z.string().min(2).max(50),
  email: z.string().email(),
  role: z.enum(['user', 'admin']),
});

export async function POST(req: Request) {
  const body = await req.json();
  const data = createUserSchema.parse(body);
  // ... implementation
}

Error Handling

// Use custom error handler
class ApiError extends Error {
  constructor(
    public statusCode: number,
    message: string,
    public code: string
  ) {
    super(message);
  }
}

function handleApiError(error: Error) {
  if (error instanceof ApiError) {
    return Response.json(
      { error: { code: error.code, message: error.message } },
      { status: error.statusCode }
    );
  }
  // Log unexpected errors
  console.error(error);
  return Response.json(
    { error: { code: 'INTERNAL_ERROR', message: 'An error occurred' } },
    { status: 500 }
  );
}

Components

Component Structure

interface Props {
  title: string;
  items: Item[];
  onSelect: (id: string) => void;
  isLoading?: boolean;
}

export function ItemList({ title, items, onSelect, isLoading }: Props) {
  if (isLoading) {
    return <Skeleton />;
  }

  return (
    <div>
      <h2>{title}</h2>
      {items.map(item => (
        <ItemCard key={item.id} item={item} onSelect={onSelect} />
      ))}
    </div>
  );
}

Custom Hooks

// Extract complex logic into hooks
export function useUserData(userId: string) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    fetchUser(userId)
      .then(setUser)
      .catch(setError)
      .finally(() => setIsLoading(false));
  }, [userId]);

  return { user, isLoading, error };
}

Do NOT

  • Use any type
  • Use class components
  • Put business logic in components
  • Use console.log (use logger)
  • Skip TypeScript types
  • Mix client/server components incorrectly
  • Hardcode API URLs (use env variables)

评论

加载中...

相关文章

分享:

评论

加载中...