大数跨境

.cursorrules:防止 AI 破坏您的代码库

.cursorrules:防止 AI 破坏您的代码库 索引目录
2025-12-15
1
导读:关注【索引目录】服务号,更多精彩内容等你来探索!你的 AI 助手刚刚建议了var一个严格使用 TypeScript 的项目。

关注【索引目录】服务号,更多精彩内容等你来探索!

你的 AI 助手刚刚建议了var一个严格使用 TypeScript 的项目。然后它从一个不存在的路径导入了代码。接着它又在你只使用 hooks 的代码库中使用了类组件。

问题不在于人工智能,而在于配置缺失。

现代人工智能编码工具支持项目级指令文件。但大多数开发者并不使用它们。以下是如何正确设置它们的方法。

您缺少的配置文件

不同的工具,不同的文件:


工具
配置文件
地点
光标
.cursorrules
项目根目录
GitHub Copilot
.github/copilot-instructions.md
.github/文件夹
风帆冲浪
.windsurfrules
项目根目录
克莱恩
.clinerules
项目根目录
助手
.aider.conf.yml
项目根目录


概念相同:一个文件,用于在人工智能生成任何内容之前告诉它你的项目是如何工作的。

.cursorrules:基础知识

.cursorrules在项目根目录中创建:

# Project: my-app
# Stack: Next.js 14, TypeScript, Tailwind CSS, Prisma

## Code Style
- Use functional components with hooks only
- No default exports except for pages
- Use named exports for everything else
- Prefer const arrow functions over function declarations

## Imports
- Use @/ alias for src/ imports
- Group imports: external, internal, relative, types
- No barrel imports from large modules

## TypeScript
- Strict mode enabled
- No 'any' type unless explicitly justified
- Interface for objects, type for unions

## State Management
- Zustand for global state
- React Query for server state
- useState for local UI state only

## File Naming
- Components: PascalCase.tsx
- Hooks: use[Name].ts
- Utils: camelCase.ts
- Types: [name].types.ts

现在,当您要求 Cursor “添加用户个人资料组件”时,它会生成符合这些规则的代码。

应包含哪些内容

有效.cursorrules文件涵盖:

建筑决策

## Architecture
- Feature-based folder structure (src/features/[feature]/)
- Co-locate tests with source files
- Shared components in src/components/ui/

依赖关系及其使用

## Key Dependencies
- Data fetching: @tanstack/react-query (useQuery, useMutation)
- Forms: react-hook-form + zod validation
- Date handling: date-fns (not moment, not dayjs)
- HTTP client: ky (not axios, not fetch)

需要避免的反模式

## DO NOT
- Use CSS modules (we use Tailwind)
- Use Redux (we use Zustand)
- Use relative imports beyond one level (use @/ alias)
- Create god components over 200 lines
- Use useEffect for data fetching

命名规则

## Naming
- Boolean props: is[State], has[Feature], can[Action]
- Event handlers: handle[Event] or on[Event]
- Async functions: fetch[Resource], create[Resource]

GitHub Copilot 使用说明

Copilot 使用 Markdown .github/copilot-instructions.md

# Copilot Instructions

## Project Context
This is a Next.js 14 application using the App Router.
All components are Server Components unless marked with 'use client'.

## Code Generation Rules

### TypeScript
- Always use strict TypeScript
- Define return types for all functions
- Use `satisfies` over type assertions when possible

### React Patterns
- Prefer Server Components for data fetching
- Use Suspense boundaries for loading states
- Keep Client Components small and leaf-level

### File Structure
When creating new features:
1. Create folder in src/features/[name]/
2. Add index.ts barrel file
3. Co-locate types in [name].types.ts
4. Co-locate tests in __tests__/

### Testing
- Use Vitest for unit tests
- Use Playwright for E2E
- Mock API calls with MSW

真实世界前后对比

我花了两个小时调试 Cursor 在一个纯 hooks 项目中不断生成类组件的原因。结果修复只用了 30 秒——一个.cursorrules文件。

任务:创建一个带有加载状态的用户头像组件

没有 .cursorrules

import React, { useState, useEffect } from 'react';
import './Avatar.css';

class Avatar extends React.Component {
  state = { loading: true, error: false };

  componentDidMount() {
    // ...
  }

  render() {
    return <div className="avatar-container">...</div>;
  }
}

export default Avatar;

问题:类组件、CSS 文件、默认导出、没有 TypeScript。

使用 .cursorrules

'use client';

import { useState } from 'react';
import { cn } from '@/lib/utils';

interface AvatarProps {
  src: string;
  alt: string;
  size?: 'sm' | 'md' | 'lg';
  fallback?: string;
}

export function Avatar({ src, alt, size = 'md', fallback }: AvatarProps) {
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const sizeClasses = {
    sm: 'h-8 w-8',
    md: 'h-12 w-12',
    lg: 'h-16 w-16',
  };

  return (
    <div className={cn('relative rounded-full overflow-hidden', sizeClasses[size])}>
      {isLoading && (
        <div className="absolute inset-0 bg-gray-200 animate-pulse" />
      )}
      {hasError ? (
        <div className="flex items-center justify-center h-full bg-gray-100">
          {fallback ?? alt.charAt(0)}
        </div>
      ) : (
        <img
          src={src}
          alt={alt}
          onLoad={() => setIsLoading(false)}
          onError={() => setHasError(true)}
          className="h-full w-full object-cover"
        />
      )}
    </div>
  );
}

匹配项:函数式组件、Tailwind、命名导出、TypeScript 接口、正确的命名约定。

高级模式

使用章节来划分代码库的不同部分:

## API Routes (src/app/api/)
- Always validate input with zod
- Return consistent error shapes: { error: string, code: string }
- Use HTTP status codes correctly
- Log errors to external service

## Database (src/db/)
- Use Prisma transactions for multi-step operations
- Never expose internal IDs in API responses
- Use soft deletes (deletedAt) not hard deletes

## Next.js 14 Specifics
- Use App Router patterns (not Pages Router)
- Prefer Server Actions over API routes for mutations
- Use 'use server' directive for server actions

## PR Requirements
- Components must have JSDoc description
- New features need tests
- Breaking changes need migration notes

常见错误

太模糊了。

# Bad
Write good code and follow best practices.

过于冗长

# Bad  
When writing React components, you should always remember that 
functional components are preferred because they are more modern
and align with React's direction as a library, and hooks provide
a cleaner way to manage state and side effects compared to the
older class-based approach which required lifecycle methods...

与项目现实相矛盾

# Bad (if your codebase actually uses axios)
Use fetch API for all HTTP requests

请检查规则是否与实际代码库相符。如果.cursorrules规则与现有代码的执行方式不同,AI 将会感到困惑。

维护

.cursorrules这是文档。如果忽略它,它会失效。

更新时间:

  • 添加主要依赖项
  • 改变架构模式
  • 更新框架版本
  • 采纳新惯例

添加到您的公关工作清单:

- [ ] Updated .cursorrules if conventions changed

快速设置清单


查看
物品
列出的堆栈和版本
导入别名已记录
组件模式定义
指定的状态管理方法
文件命名规则
列举一些反模式(不应该做什么)
测试框架和模式
主要依赖项及使用说明


入门模板

复制此内容并进行自定义:

# Project: [name]
# Stack: [framework], [language], [styling]
# Last updated: [date]

## Code Style
- [component pattern]
- [export pattern]
- [function style]

## Imports
- Alias: @/ → src/
- Order: external → internal → relative → types

## TypeScript
- [strict mode?]
- [type vs interface preference]

## State Management
- Global: [library]
- Server: [library]
- Local: useState

## Key Dependencies
- [package]: [what for]

## DO NOT
- [anti-pattern 1]
- [anti-pattern 2]

## File Structure
[your structure]

结论

只需五分钟的配置,就能节省数小时修复与项目不匹配的 AI 生成代码的时间。

你的.cursorrules文件就是代码库中人工智能的使用手册。编写它时要像指导新开发人员一样——明确的限制、具体的示例、明确的反模式。

人工智能只能遵循它已知的规则。


关注【索引目录】服务号,更多精彩内容等你来探索!


【声明】内容源于网络
0
0
索引目录
索引目录是一家专注于医疗、技术开发、物联网应用等领域的创新型公司。我们致力于为客户提供高质量的服务和解决方案,推动技术与行业发展。
内容 444
粉丝 0
索引目录 索引目录是一家专注于医疗、技术开发、物联网应用等领域的创新型公司。我们致力于为客户提供高质量的服务和解决方案,推动技术与行业发展。
总阅读12
粉丝0
内容444