Cursor 配置完全指南

Cursor 配置完全指南

全方位解析 Cursor 的配置体系,从入门到精通


目录


配置体系概览

Cursor 配置层级

scss 复制代码
全局配置 (Global)
    ↓
工作区配置 (Workspace)
    ↓
项目配置 (Project)
    ↓
文件级配置 (File)

配置文件位置

bash 复制代码
~/.cursor/                          # Cursor 全局配置目录
├── settings.json                   # 全局设置
├── keybindings.json               # 全局快捷键
└── extensions/                     # 扩展配置

项目根目录/
├── .cursor/                        # 项目级 Cursor 配置
│   ├── rules/                      # AI 规则文件
│   │   ├── .cursorrules           # 主规则文件
│   │   └── projects/              # 项目规则
│   │       ├── sub-rules/         # 子规则
│   │       └── templates/         # 模板规则
│   ├── mcp.json                   # MCP 配置
│   └── settings.json              # 项目设置
├── .cursorignore                  # 忽略文件配置
└── .vscode/                       # VSCode 兼容配置
    ├── settings.json              # 编辑器设置
    └── extensions.json            # 推荐扩展

配置优先级

复制代码
文件级配置 > 项目配置 > 工作区配置> 全局配置

Cursor Rules 配置

什么是 Cursor Rules?

Cursor Rules 是告诉 AI 如何理解和处理你的项目的指令集,类似于给 AI 助手的"工作手册"。

规则文件类型

1. .cursorrules - 主规则文件

位置 : 项目根目录或 .cursor/ 目录

作用: 定义项目的核心规则,AI 会自动读取

示例:

markdown 复制代码
# 项目基本信息

项目名称: Haiyi App
技术栈: Vue 3 + TypeScript + uni-app
目标平台: 微信小程序

# 代码规范

## 命名规范
- 组件: PascalCase (如 UserCard.vue)
- 文件: kebab-case (如 user-card.ts)
- 变量/函数: camelCase (如 getUserInfo)
- 常量: UPPER_SNAKE_CASE (如 MAX_COUNT)

## TypeScript 规范
- 严格模式: 启用 strict: true
- 禁止使用 any,必要时使用 unknown
- 所有函数必须有类型注解
- 接口使用 I 前缀 (如 IUserInfo)

## Vue 3 规范
- 使用 <script setup lang="ts">
- 优先使用 Composition API
- Props 使用 defineProps<Props>()
- Emits 使用 defineEmits<Emits>()

## 文件组织
- 页面: src/pages/
- 组件: src/components/
- API: src/api/
- 类型: src/types/
- 工具: src/utils/
- Composables: src/composables/

# 开发约束

- 单个函数不超过 50 行
- 单个文件不超过 300 行
- 所有异步操作必须有错误处理
- 组件必须有 JSDoc 注释
- 不要自行添加未要求的功能

# Git 规范

提交格式: <type>(<scope>): <description>

类型:
- feat: 新功能
- fix: 修复
- refactor: 重构
- docs: 文档
- style: 格式
- test: 测试
- chore: 其他

所有 commit 必须包含签名:
Signed-off-by: Name <email@example.com>
2. .mdc - Markdown 规则文件

位置 : .cursor/rules/projects/sub-rules/

作用: 模块化的规则文件,可以按功能拆分

优势:

  • 支持更复杂的结构
  • 可以被其他规则引用
  • 便于团队协作和维护

示例 : code-rules.mdc

markdown 复制代码
---
title: 代码规范
description: 项目代码编写规范
version: 1.0.0
author: Team
---

# 代码规范

## TypeScript 类型定义

### 接口定义

```typescript
// ✅ 推荐
interface IUserInfo {
  id: number
  name: string
  avatar?: string
  createdAt: Date
}

// ❌ 不推荐
interface UserInfo {
  id: any
  name: string
}

类型别名

typescript 复制代码
// ✅ 联合类型使用 type
type Status = 'pending' | 'success' | 'error'

// ✅ 复杂类型使用 type
type ApiResponse<T> = {
  code: number
  data: T
  message: string
}

Vue 组件规范

Props 定义

typescript 复制代码
// ✅ 推荐
interface Props {
  title: string
  count?: number
}

const props = withDefaults(defineProps<Props>(), {
  count: 0
})

// ❌ 不推荐
const props = defineProps({
  title: String,
  count: Number
})

Emits 定义

typescript 复制代码
// ✅ 推荐
const emit = defineEmits<{
  (e: 'update', value: number): void
  (e: 'close'): void
}>()

// ❌ 不推荐
const emit = defineEmits(['update', 'close'])

错误处理

异步操作

typescript 复制代码
// ✅ 推荐
const fetchData = async () => {
  try {
    const res = await api.getData()
    return res.data
  } catch (error) {
    console.error('获取数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
    throw error
  }
}

// ❌ 不推荐
const fetchData = async () => {
  const res = await api.getData()
  return res.data
}

性能优化

列表渲染

vue 复制代码
<!-- ✅ 推荐 -->
<view
  v-for="item in list"
  :key="item.id"
  v-memo="[item.status]"
>
  {{ item.name }}
</view>

<!-- ❌ 不推荐 -->
<view v-for="(item, index) in list" :key="index">
  {{ item.name }}
</view>

计算属性

typescript 复制代码
// ✅ 推荐
const filteredList = computed(() => {
  return list.value.filter(item => item.status === 'active')
})

// ❌ 不推荐
const filteredList = () => {
  return list.value.filter(item => item.status === 'active')
}
yaml 复制代码
#### 3. 特殊规则文件

**`animation-effects.mdc`** - 动画效果规则

```markdown
---
title: 动画效果规范
trigger: ["动画效果", "增加动效", "增加动画效果"]
---

# 动画效果规范

## 触发方式

当用户说"动画效果"、"增加动效"或"增加动画效果"时,自动应用此规则。

## 动画原则

1. **性能优先**: 使用 transform 和 opacity,避免触发重排
2. **时长适中**: 150-300ms 为最佳体验
3. **缓动函数**: 使用 ease-out 让动画更自然
4. **减少动画**: 尊重用户的 prefers-reduced-motion 设置

## 常用动画

### 淡入淡出

```scss
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

滑动

scss 复制代码
.slide-up-enter-active,
.slide-up-leave-active {
  transition: transform 0.3s ease-out;
}

.slide-up-enter-from {
  transform: translateY(100%);
}

.slide-up-leave-to {
  transform: translateY(-100%);
}

缩放

scss 复制代码
.scale-enter-active,
.scale-leave-active {
  transition: transform 0.2s ease-out;
}

.scale-enter-from,
.scale-leave-to {
  transform: scale(0.8);
}

Vue 3 Transition

vue 复制代码
<template>
  <Transition name="fade">
    <view v-if="show">内容</view>
  </Transition>
</template>

uni-app 动画

typescript 复制代码
const animation = uni.createAnimation({
  duration: 300,
  timingFunction: 'ease-out'
})

animation.translateY(-100).opacity(0).step()

animationData.value = animation.export()
yaml 复制代码
**`figma-to-vue.mdc`** - Figma 转 Vue 规则

```markdown
---
title: Figma 到 Vue 开发流程
trigger: ["figma2vue", "从Figma生成页面"]
---

# Figma 到 Vue 开发流程

## 触发方式

使用 "figma2vue" 或 "从Figma生成页面" 触发此工作流。

## 工作流程

### 第1步: 分析设计稿

1. 获取 Figma 设计稿链接
2. 分析页面结构和组件
3. 识别可复用组件
4. 确定响应式断点

### 第2步: 组件拆分

按以下优先级拆分组件:

1. **基础组件** (Base)
   - 按钮、输入框、标签等
   - 高复用、无业务逻辑

2. **业务组件** (Business)
   - 用户卡片、商品卡片等
   - 中等复用、包含业务逻辑

3. **页面组件** (Page)
   - 页面特定组件
   - 低复用、页面专用

### 第3步: 样式转换

#### Figma 设计 → CSS/SCSS

| Figma 属性 | CSS 属性 |
|-----------|---------|
| Frame | div/view |
| Auto Layout | flex |
| Padding | padding |
| Gap | gap |
| Fill | background |
| Stroke | border |
| Effects → Drop Shadow | box-shadow |
| Effects → Blur | backdrop-filter |

#### 单位转换

```scss
// Figma 使用 px,小程序使用 rpx
// 设计稿宽度 750px = 100vw

@function px2rpx($px) {
  @return $px * 2rpx;
}

// Figma: 16px → SCSS: 32rpx
.text {
  font-size: px2rpx(16); // 32rpx
}

第4步: 实现组件

vue 复制代码
<script setup lang="ts">
// 1. 定义 Props
interface Props {
  title: string
  // ... 从 Figma 提取的属性
}

// 2. 定义 Emits
const emit = defineEmits<{
  (e: 'click'): void
}>()

// 3. 实现逻辑
</script>

<template>
  <!-- 4. 实现模板 -->
</template>

<style lang="scss" scoped>
/* 5. 实现样式 */
</style>

第5步: 验证与优化

  • 视觉还原度 > 95%
  • 响应式适配
  • 交互动画
  • 性能优化
  • 无障碍支持
yaml 复制代码
**`multi-lang.mdc`** - 多语言规则

```markdown
---
title: 多语言国际化
trigger: ["跑多语言", "翻译脚本"]
---

# 多语言国际化规范

## 触发方式

使用 "跑多语言" 或 "翻译脚本" 触发多语言处理。

## 目录结构

src/ ├── locales/ │ ├── zh-CN.json # 简体中文 │ ├── zh-TW.json # 繁体中文 │ ├── en-US.json # 英语 │ └── ja-JP.json # 日语 └── utils/ └── i18n.ts # 国际化工具

bash 复制代码
## 语言文件格式

```json
{
  "common": {
    "confirm": "确认",
    "cancel": "取消",
    "save": "保存",
    "delete": "删除"
  },
  "pages": {
    "home": {
      "title": "首页",
      "welcome": "欢迎使用 {appName}"
    }
  },
  "errors": {
    "network": "网络错误,请稍后重试",
    "auth": "登录已过期,请重新登录"
  }
}

使用方式

typescript 复制代码
import { t } from '@/utils/i18n'

// 基础使用
const title = t('pages.home.title')

// 带参数
const welcome = t('pages.home.welcome', { appName: 'Haiyi' })

// 在模板中
<template>
  <view>{{ t('common.confirm') }}</view>
</template>

自动提取脚本

javascript 复制代码
// scripts/extract-i18n.js
// 自动提取代码中的中文文本
// 生成语言文件

翻译工作流

  1. 开发时使用中文
  2. 运行提取脚本
  3. 使用翻译 API 自动翻译
  4. 人工校对关键文本
  5. 提交语言文件
bash 复制代码
### 规则文件引用

在主规则文件中引用子规则:

```markdown
# Shortcuts

- 使用 '跑多语言' 或 '翻译脚本' 对应规则 [multi-lang.mdc](mdc:.cursor/rules/projects/sub-rules/multi-lang.mdc)
- 使用 '动画效果' 或 '增加动效' 触发动画规则 [animation-effects.mdc](mdc:.cursor/rules/projects/sub-rules/animation-effects.mdc)
- 使用 'figma2vue' 触发 Figma 转换流程 [figma-to-vue.mdc](mdc:.cursor/rules/projects/sub-rules/figma-to-vue.mdc)

规则最佳实践

1. 结构化组织
bash 复制代码
.cursor/rules/
├── .cursorrules                    # 主规则入口
└── projects/
    ├── sub-rules/                  # 子规则
    │   ├── code-rules.mdc         # 代码规范
    │   ├── style-guidelines.mdc   # 样式规范
    │   ├── api-standards.mdc      # API 规范
    │   ├── animation-effects.mdc  # 动画规范
    │   ├── figma-to-vue.mdc       # Figma 工作流
    │   └── multi-lang.mdc         # 多语言规范
    └── templates/                  # 模板规则
        ├── component-template.mdc  # 组件模板
        ├── page-template.mdc       # 页面模板
        └── api-template.mdc        # API 模板
2. 规则优先级
markdown 复制代码
# 在 .cursorrules 中定义优先级

## 强制规则 (Must)
- 必须使用 TypeScript
- 必须有错误处理
- 必须有类型定义

## 推荐规则 (Should)
- 应该添加注释
- 应该使用 Composition API
- 应该遵循命名规范

## 可选规则 (May)
- 可以使用第三方库
- 可以自定义样式
3. 规则版本管理
markdown 复制代码
---
version: 1.0.0
last_updated: 2026-01-14
changelog:
  - 1.0.0: 初始版本
  - 1.1.0: 添加 TypeScript 严格模式
  - 1.2.0: 添加性能优化规范
---
4. 团队协作规则
markdown 复制代码
# 团队规范

## 代码审查清单
- [ ] 符合命名规范
- [ ] 有完整的类型定义
- [ ] 有错误处理
- [ ] 有必要的注释
- [ ] 通过 ESLint 检查
- [ ] 通过单元测试

## 提交规范
- 提交前运行 `pnpm lint`
- 提交信息符合规范
- 包含签名信息

## 分支策略
- main: 生产环境
- develop: 开发环境
- feature/*: 功能分支
- hotfix/*: 紧急修复

MCP (Model Context Protocol) 配置

什么是 MCP?

MCP (Model Context Protocol) 是 Anthropic 推出的开放协议,让 AI 能够安全地连接外部数据源和工具。

MCP 架构

arduino 复制代码
┌─────────────┐
│   Cursor    │
│   (Client)  │
└──────┬──────┘
       │
       │ MCP Protocol
       │
┌──────┴──────┐
│  MCP Server │
└──────┬──────┘
       │
       ├─── Database
       ├─── File System
       ├─── APIs
       └─── Tools

MCP 配置文件

位置 : .cursor/mcp.json~/.cursor/mcp.json

基础配置:

json 复制代码
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/projects"
      ]
    },
    "github": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-github"
      ],
      "env": {
        "GITHUB_TOKEN": "your_github_token"
      }
    },
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost/mydb"
      ]
    }
  }
}

常用 MCP Servers

1. Filesystem Server

功能: 让 AI 访问本地文件系统

json 复制代码
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/path/to/allowed/directory"
      ]
    }
  }
}

使用场景:

  • 读取项目文档
  • 分析日志文件
  • 处理配置文件
2. GitHub Server

功能: 让 AI 访问 GitHub 仓库

json 复制代码
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_xxxxxxxxxxxx"
      }
    }
  }
}

使用场景:

  • 查看 Issues 和 PRs
  • 分析代码历史
  • 自动创建 PR
3. Database Servers

PostgreSQL:

json 复制代码
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://user:password@localhost:5432/dbname"
      ]
    }
  }
}

SQLite:

json 复制代码
{
  "mcpServers": {
    "sqlite": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sqlite",
        "/path/to/database.db"
      ]
    }
  }
}

使用场景:

  • 查询数据库结构
  • 生成 SQL 语句
  • 数据分析
json 复制代码
{
  "mcpServers": {
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "your_brave_api_key"
      }
    }
  }
}

使用场景:

  • 搜索最新技术文档
  • 查找解决方案
  • 获取实时信息
5. Slack Server
json 复制代码
{
  "mcpServers": {
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-token",
        "SLACK_TEAM_ID": "T1234567"
      }
    }
  }
}

使用场景:

  • 读取团队消息
  • 发送通知
  • 同步工作进度
6. Google Drive Server
json 复制代码
{
  "mcpServers": {
    "gdrive": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-gdrive"],
      "env": {
        "GOOGLE_CLIENT_ID": "your_client_id",
        "GOOGLE_CLIENT_SECRET": "your_client_secret"
      }
    }
  }
}
7. Memory Server
json 复制代码
{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"]
    }
  }
}

功能: 让 AI 在会话间保持记忆

自定义 MCP Server

创建自定义 Server
typescript 复制代码
// my-mcp-server.ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

const server = new Server(
  {
    name: 'my-custom-server',
    version: '1.0.0'
  },
  {
    capabilities: {
      tools: {}
    }
  }
)

// 定义工具
server.setRequestHandler('tools/list', async () => {
  return {
    tools: [
      {
        name: 'get_project_stats',
        description: '获取项目统计信息',
        inputSchema: {
          type: 'object',
          properties: {
            projectPath: {
              type: 'string',
              description: '项目路径'
            }
          }
        }
      }
    ]
  }
})

// 实现工具
server.setRequestHandler('tools/call', async (request) => {
  if (request.params.name === 'get_project_stats') {
    const stats = await getProjectStats(request.params.arguments.projectPath)
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(stats, null, 2)
        }
      ]
    }
  }
})

// 启动服务器
const transport = new StdioServerTransport()
await server.connect(transport)
配置自定义 Server
json 复制代码
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["/path/to/my-mcp-server.js"]
    }
  }
}

MCP 安全配置

json 复制代码
{
  "mcpServers": {
    "secure-filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/allowed/path"
      ],
      "security": {
        "allowedOperations": ["read"],
        "deniedPaths": [
          "/allowed/path/.env",
          "/allowed/path/secrets"
        ]
      }
    }
  }
}

MCP 最佳实践

  1. 最小权限原则: 只授予必要的权限
  2. 环境变量管理 : 使用 .env 文件管理敏感信息
  3. 路径限制: 限制文件系统访问范围
  4. 日志记录: 记录 MCP 操作日志
  5. 定期审计: 定期检查 MCP 配置和使用情况

工作区配置

.cursorignore 配置

作用: 告诉 Cursor 哪些文件不需要被 AI 索引

python 复制代码
# 依赖目录
node_modules/
dist/
build/
.next/

# 环境文件
.env
.env.local
.env.*.local

# 日志文件
*.log
logs/

# 临时文件
*.tmp
*.temp
.cache/

# 测试覆盖率
coverage/

# 编辑器
.vscode/
.idea/

# 系统文件
.DS_Store
Thumbs.db

# 大文件
*.zip
*.tar.gz
*.mp4
*.mov

# 敏感文件
secrets/
private/
*.key
*.pem

# 编译产物
*.min.js
*.min.css
*.map

工作区设置

.cursor/settings.json:

json 复制代码
{
  // AI 设置
  "cursor.ai.model": "claude-3.5-sonnet",
  "cursor.ai.temperature": 0.7,
  "cursor.ai.maxTokens": 4096,
  
  // 代码补全
  "cursor.completion.enabled": true,
  "cursor.completion.triggerCharacters": [".", "(", "[", "{"],
  "cursor.completion.debounceDelay": 150,
  
  // Chat 设置
  "cursor.chat.contextLines": 50,
  "cursor.chat.includeOpenFiles": true,
  "cursor.chat.includeRecentFiles": true,
  
  // 索引设置
  "cursor.index.enabled": true,
  "cursor.index.excludePatterns": [
    "**/node_modules/**",
    "**/dist/**",
    "**/*.min.js"
  ],
  
  // 隐私设置
  "cursor.privacy.enableTelemetry": false,
  "cursor.privacy.shareCodeContext": false,
  
  // 编辑器设置
  "editor.fontSize": 14,
  "editor.tabSize": 2,
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  
  // 文件关联
  "files.associations": {
    "*.vue": "vue",
    "*.wxml": "html",
    "*.wxss": "css"
  }
}

AI 模型配置

模型选择

全局模型配置:

json 复制代码
{
  "cursor.ai.defaultModel": "claude-3.5-sonnet",
  "cursor.ai.models": {
    "chat": "claude-3.5-sonnet",
    "completion": "gpt-4-turbo",
    "edit": "gpt-3.5-turbo"
  }
}

可用模型列表

模型 适用场景 优势 劣势
Claude 3.5 Sonnet 代码审查、重构 理解力强、注重细节 成本较高
GPT-4 Turbo 架构设计、算法 推理能力强 速度较慢
GPT-3.5 Turbo 简单任务、补全 速度快、成本低 理解力一般
Claude 3 Haiku 重复性任务 速度快、成本低 能力有限

自定义模型参数

json 复制代码
{
  "cursor.ai.customModels": [
    {
      "name": "my-gpt4",
      "provider": "openai",
      "model": "gpt-4-turbo-preview",
      "apiKey": "${OPENAI_API_KEY}",
      "temperature": 0.3,
      "maxTokens": 8192
    },
    {
      "name": "my-claude",
      "provider": "anthropic",
      "model": "claude-3-5-sonnet-20241022",
      "apiKey": "${ANTHROPIC_API_KEY}",
      "temperature": 0.7,
      "maxTokens": 4096
    }
  ]
}

模型切换策略

json 复制代码
{
  "cursor.ai.modelStrategy": {
    "simple": "gpt-3.5-turbo",
    "complex": "gpt-4-turbo",
    "review": "claude-3.5-sonnet",
    "refactor": "claude-3.5-sonnet"
  }
}

快捷键与命令配置

默认快捷键

快捷键 功能 说明
Cmd/Ctrl + K 快速编辑 内联编辑,适合小改动
Cmd/Ctrl + L 打开 Chat 聊天模式,适合复杂问题
Cmd/Ctrl + I 内联补全 智能代码补全
Cmd/Ctrl + Shift + L 新建 Chat 开启新对话
Cmd/Ctrl + / 注释切换 添加/删除注释
Cmd/Ctrl + D 选择下一个 多光标编辑

自定义快捷键

keybindings.json:

json 复制代码
[
  {
    "key": "cmd+shift+a",
    "command": "cursor.ai.chat",
    "when": "editorTextFocus"
  },
  {
    "key": "cmd+shift+r",
    "command": "cursor.ai.refactor",
    "when": "editorHasSelection"
  },
  {
    "key": "cmd+shift+e",
    "command": "cursor.ai.explain",
    "when": "editorHasSelection"
  },
  {
    "key": "cmd+shift+t",
    "command": "cursor.ai.generateTest",
    "when": "editorTextFocus"
  },
  {
    "key": "cmd+shift+d",
    "command": "cursor.ai.generateDocs",
    "when": "editorTextFocus"
  }
]

自定义命令

.cursor/commands.json:

json 复制代码
{
  "commands": [
    {
      "name": "生成组件",
      "command": "cursor.ai.chat",
      "prompt": "基于当前文件创建一个 Vue 3 组件,使用 TypeScript 和 Composition API",
      "keybinding": "cmd+shift+c"
    },
    {
      "name": "优化性能",
      "command": "cursor.ai.chat",
      "prompt": "分析当前代码的性能问题并提供优化建议",
      "keybinding": "cmd+shift+p"
    },
    {
      "name": "添加测试",
      "command": "cursor.ai.chat",
      "prompt": "为当前函数生成单元测试,使用 Vitest",
      "keybinding": "cmd+shift+t"
    }
  ]
}

实用配置案例

案例 1: Vue 3 + TypeScript 项目配置

.cursorrules:

markdown 复制代码
# Vue 3 + TypeScript 项目

## 技术栈
- Vue 3.4+
- TypeScript 5.3+
- Vite 5.0+
- Pinia 2.1+
- Vue Router 4.2+

## 代码规范
- 使用 <script setup lang="ts">
- 使用 Composition API
- 所有组件必须有类型定义
- Props 使用 defineProps<Props>()
- Emits 使用 defineEmits<Emits>()

## 文件组织
src/
├── components/     # 组件
├── views/         # 页面
├── composables/   # 组合式函数
├── stores/        # Pinia stores
├── types/         # 类型定义
└── utils/         # 工具函数

## 命名规范
- 组件: PascalCase
- 文件: kebab-case
- 变量: camelCase
- 常量: UPPER_SNAKE_CASE

.cursor/settings.json:

json 复制代码
{
  "cursor.ai.model": "claude-3.5-sonnet",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "files.associations": {
    "*.vue": "vue"
  },
  "[vue]": {
    "editor.defaultFormatter": "Vue.volar"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

案例 2: uni-app 小程序项目配置

.cursorrules:

markdown 复制代码
# uni-app 小程序项目

## 技术栈
- uni-app (Vue 3)
- TypeScript
- Pinia
- uni-ui

## 平台
- 微信小程序
- 支付宝小程序
- 字节跳动小程序

## 开发规范
- 使用 uni. API 而非原生 API
- 使用 rpx 单位
- 使用条件编译处理平台差异
- 页面文件放在 pages/ 目录

## 性能要求
- 主包 < 2MB
- 单个分包 < 2MB
- 图片使用 CDN
- 列表使用虚拟滚动

## 条件编译
// #ifdef MP-WEIXIN
// 微信小程序代码
// #endif

// #ifdef H5
// H5 代码
// #endif

.cursorignore:

bash 复制代码
node_modules/
dist/
unpackage/
.hbuilderx/
*.log

案例 3: 全栈项目配置

项目结构:

arduino 复制代码
project/
├── frontend/
│   └── .cursor/
│       ├── rules/
│       │   └── .cursorrules
│       └── settings.json
├── backend/
│   └── .cursor/
│       ├── rules/
│       │   └── .cursorrules
│       └── settings.json
└── .cursor/
    ├── mcp.json
    └── settings.json

根目录 .cursorrules:

markdown 复制代码
# 全栈项目

## 项目结构
- frontend/: Vue 3 前端
- backend/: Node.js 后端
- shared/: 共享类型和工具

## 开发规范
- 使用 Monorepo 管理
- 共享类型定义
- 统一代码规范
- 统一 Git 规范

## API 规范
- RESTful API
- 统一响应格式
- 统一错误处理
- API 文档自动生成

MCP 配置:

json 复制代码
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost/mydb"
      ]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

第三方资源获取

官方资源

Cursor 官方
MCP 官方

社区资源

Cursor Rules 仓库
  1. Awesome Cursor Rules

  2. Cursor Rules Templates

  3. Cursor Directory

MCP Servers 集合
  1. Official MCP Servers

    bash 复制代码
    # Filesystem
    @modelcontextprotocol/server-filesystem
    
    # GitHub
    @modelcontextprotocol/server-github
    
    # PostgreSQL
    @modelcontextprotocol/server-postgres
    
    # SQLite
    @modelcontextprotocol/server-sqlite
    
    # Brave Search
    @modelcontextprotocol/server-brave-search
    
    # Slack
    @modelcontextprotocol/server-slack
    
    # Google Drive
    @modelcontextprotocol/server-gdrive
  2. Community MCP Servers

配置分享平台
  1. Cursor Settings

  2. Gist Collections

    • 搜索: "cursor rules" 或 "cursorrules"
    • 平台: GitHub Gist

推荐规则集

1. Vue 3 + TypeScript
bash 复制代码
# 下载
curl -o .cursorrules https://raw.githubusercontent.com/cursor-rules/templates/main/vue3-typescript.cursorrules
2. React + TypeScript
bash 复制代码
curl -o .cursorrules https://raw.githubusercontent.com/cursor-rules/templates/main/react-typescript.cursorrules
3. Node.js + Express
bash 复制代码
curl -o .cursorrules https://raw.githubusercontent.com/cursor-rules/templates/main/nodejs-express.cursorrules
4. Python + FastAPI
bash 复制代码
curl -o .cursorrules https://raw.githubusercontent.com/cursor-rules/templates/main/python-fastapi.cursorrules

工具和插件

1. Cursor Rules Generator
bash 复制代码
npm install -g cursor-rules-generator

# 使用
cursor-rules-generator --framework vue3 --language typescript
2. MCP Server CLI
bash 复制代码
npm install -g @modelcontextprotocol/cli

# 列出可用 servers
mcp list

# 安装 server
mcp install filesystem

# 配置 server
mcp config
3. Cursor Config Manager
bash 复制代码
npm install -g cursor-config-manager

# 导出配置
cursor-config export

# 导入配置
cursor-config import config.json

# 分享配置
cursor-config share

最佳实践

1. 规则文件管理

版本控制
bash 复制代码
# 提交规则文件
git add .cursor/
git add .cursorrules
git commit -m "docs: 更新 Cursor 规则"

# 忽略敏感配置
echo ".cursor/mcp.json" >> .gitignore
echo ".cursor/settings.json" >> .gitignore
团队协作
markdown 复制代码
# 在 README.md 中说明

## Cursor 配置

本项目使用 Cursor 进行开发,请按以下步骤配置:

1. 安装 Cursor: https://cursor.sh
2. 打开项目,Cursor 会自动读取 `.cursorrules`
3. 配置 MCP (可选):
   ```bash
   cp .cursor/mcp.example.json .cursor/mcp.json
   # 编辑 mcp.json,填入你的 API keys
  1. 安装推荐扩展 (见 .vscode/extensions.json)

快捷指令

  • figma2vue: 从 Figma 生成页面
  • 跑多语言: 运行多语言脚本
  • 动画效果: 添加动画效果
shell 复制代码
### 2. 配置分层

全局配置 (~/.cursor/) ├── 个人偏好 ├── 通用规则 └── API Keys

项目配置 (project/.cursor/) ├── 项目规则 ├── 团队规范 └── 工作流配置

文件配置 (inline comments) └── 特殊说明

makefile 复制代码
### 3. 安全实践

#### 环境变量管理

```bash
# .env
GITHUB_TOKEN=ghp_xxxxxxxxxxxx
ANTHROPIC_API_KEY=sk-xxxxxxxxxxxx
OPENAI_API_KEY=sk-xxxxxxxxxxxx

# .cursor/mcp.json
{
  "mcpServers": {
    "github": {
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}
敏感信息保护
bash 复制代码
# .gitignore
.env
.env.local
.cursor/mcp.json
.cursor/settings.json
*.key
*.pem
secrets/

4. 性能优化

索引优化
json 复制代码
{
  "cursor.index.excludePatterns": [
    "**/node_modules/**",
    "**/dist/**",
    "**/build/**",
    "**/.next/**",
    "**/*.min.js",
    "**/*.min.css",
    "**/*.map"
  ],
  "cursor.index.maxFileSize": 1048576,
  "cursor.index.maxFiles": 10000
}
缓存管理
bash 复制代码
# 清理 Cursor 缓存
rm -rf ~/.cursor/cache

# 重建索引
Cmd/Ctrl + Shift + P → "Cursor: Rebuild Index"

5. 调试技巧

查看 AI 上下文
css 复制代码
Cmd/Ctrl + Shift + P → "Cursor: Show AI Context"
查看规则加载状态
css 复制代码
Cmd/Ctrl + Shift + P → "Cursor: Show Loaded Rules"
查看 MCP 连接状态
css 复制代码
Cmd/Ctrl + Shift + P → "Cursor: Show MCP Status"

常见问题

Q1: Cursor 不读取我的 .cursorrules 文件?

解决方案:

  1. 检查文件位置(项目根目录或 .cursor/ 目录)
  2. 检查文件名(.cursorrules 不是 cursorrules
  3. 重启 Cursor
  4. 重建索引: Cmd/Ctrl + Shift + P → "Cursor: Rebuild Index"

Q2: MCP Server 连接失败?

解决方案:

  1. 检查 mcp.json 语法
  2. 确认 server 已安装: npx @modelcontextprotocol/server-xxx --version
  3. 检查环境变量
  4. 查看 Cursor 日志: HelpToggle Developer ToolsConsole

Q3: AI 生成的代码不符合规范?

解决方案:

  1. 检查规则文件是否清晰明确
  2. 在提示词中明确引用规则
  3. 使用更具体的约束条件
  4. 分步骤实现,每步验证

Q4: 如何在团队中共享配置?

解决方案:

  1. .cursorrules 提交到 Git
  2. 创建 mcp.example.json 作为模板
  3. 在 README 中说明配置步骤
  4. 使用环境变量管理敏感信息

Q5: Cursor 占用内存太大?

解决方案:

  1. 优化 .cursorignore,排除大文件
  2. 减少索引文件数量
  3. 关闭不需要的 MCP servers
  4. 定期清理缓存

Q6: 如何切换不同的 AI 模型?

解决方案:

yaml 复制代码
方法 1: 在 Chat 中点击模型选择器
方法 2: 设置默认模型 (settings.json)
方法 3: 使用快捷键切换 (自定义)

Q7: 规则文件太长,AI 理解不准确?

解决方案:

  1. 拆分成多个 .mdc 文件
  2. 使用优先级标记(Must/Should/May)
  3. 精简规则,只保留关键约束
  4. 使用示例代码而非长篇描述

Q8: 如何调试自定义 MCP Server?

解决方案:

bash 复制代码
# 直接运行 server 查看输出
node my-mcp-server.js

# 使用 MCP Inspector
npx @modelcontextprotocol/inspector node my-mcp-server.js

# 查看 Cursor 日志
Help → Toggle Developer Tools → Console

总结

配置优先级

markdown 复制代码
1. 明确的提示词 > 规则文件
2. 项目规则 > 全局规则
3. 具体规则 > 通用规则
4. 约束条件 > 建议性规则

配置原则

  1. 简洁明确: 规则要清晰,避免歧义
  2. 分层管理: 全局、项目、文件分层配置
  3. 安全第一: 保护敏感信息,最小权限原则
  4. 团队协作: 规则共享,统一规范
  5. 持续优化: 根据使用情况不断调整

快速开始清单

  • 创建 .cursorrules 文件
  • 配置 .cursorignore 排除无关文件
  • 设置项目规范和约束
  • 配置 MCP (可选)
  • 自定义快捷键 (可选)
  • 团队共享配置
  • 编写使用文档

进阶技巧

  • 创建模块化规则文件
  • 配置自定义 MCP Server
  • 设置模型切换策略
  • 建立配置模板库
  • 自动化配置管理

Happy Coding with Cursor! 🚀

相关推荐
Gaaraa2 小时前
Vibe Coding指南
vibecoding
程序员鱼皮9 小时前
我的免费 Vibe Coding 教程,爆了!
程序员·ai编程·vibecoding
甲维斯11 小时前
Claude Code 第四篇:SKILL的创建,安装,查看
claude·vibecoding
hugo_im1 天前
写了一个 claude.md,AI 写代码终于不乱来了
claude·vibecoding
用户47949283569151 天前
拒绝傻瓜式截断 Diff:聊聊我在 AI Commit 插件里做的 7 个技术微创新
ai编程·trae·vibecoding
Captaincc1 天前
Vibe Coding 进阶:非技术人员的生存手册
程序员·vibecoding
黄林晴1 天前
Anthropic 发布 Cowork:让 AI 成为你的「虚拟同事」
openai·ai编程·vibecoding
AlienZHOU1 天前
MCP 是最大骗局?Skills 才是救星?
agent·mcp·vibecoding
猪猪拆迁队1 天前
深度实践:Spec-Coding,AI 独立完成复杂 UI 开发的可行性方案
前端·ai编程·vibecoding