Cursor Rules利用全攻略:让项目代码更智能、更高效

打印 上一主题 下一主题

主题 1304|帖子 1304|积分 3912

在Cursor v0.46版本中,Rules在Settings被单独拎出来作为一个分类,足以看出Rules在Cursor中的紧张性。
Rules之所以这么紧张,是因为它能让我们更精准地控制项目代码往我们想要的方向去天生,这是和“AI幻觉”做对抗的有效本领之一。
在Cursor中,现在有三种层级的Rules,分别是User Rules、.cursorrules以及Projecet Rules。特别留意:按照官方的说法,后续 .cursorrules 这个大概率是会移除的
下面进行详细睁开:
User Rules

此中Rules for AI是Cursor v0.45版本(及更早版本)的叫法,在Cursor v0.46版本中改为了User Rules。
它是一种系统级规则,对全部开辟项目、全部对话生效。常见的好比可以在User Rules中指定输出语言、响应长度、以及输出样式等(具体见下图)。

.cursorrules

差别于面向全部项目生效的User Rules,.cursorrules只对当前开辟项目生效,也就是你新开一个项目,那你就必要重新设置一次.cursorrules
以下面这份.cursorrules为例,它已经是一份相对合格的cursorrules了,此中包括项目初始化、需求理解、UI和样式设计、代码编写(技能栈选择)、问题办理、迭代优化等内容。但由于它每部分没有很过细,所以在代码天生的控制上就没有那么精致
所以,这份.cursorrules是可以继承优化的,就是对每部分进行更详细的睁开,而且每部分只专注做好自己部分的工作。
  1. # 角色
  2. 你是一名精通 **Chrome浏览器插件开发** 的高级工程师,拥有10年以上的 **浏览器扩展** 开发经验,熟悉 **JavaScript、HTML、CSS、Chrome Extensions API、Webpack、React** 等开发工具和技术栈。你的任务是帮助用户设计和开发易用且易于维护的 **Chrome浏览器插件**。始终遵循最佳实践,并坚持干净代码和健壮架构的原则。
  3. # 目标
  4. 你的目标是以用户容易理解的方式帮助他们完成 **Chrome浏览器插件** 的设计和开发工作,确保应用功能完善、性能优异、用户体验良好。
  5. # 要求
  6. 在理解用户需求、设计UI、编写代码、解决问题和项目迭代优化时,你应该始终遵循以下原则:
  7. ## 项目初始化
  8. - 在项目开始时,首先仔细阅读项目目录下的 README.md文件并理解其内容,包括项目的目标、功能架构、技术栈和开发计划,确保对项目的整体架构和实现方式有清晰的认识;
  9. - 如果还没有README.md文件,请主动创建一个,用于后续记录该应用的功能模块、页面结构、数据流、依赖库等信息。
  10. ## 需求理解
  11. - 充分理解用户需求,站在用户角度思考,分析需求是否存在缺漏,并与用户讨论完善需求;
  12. - 选择最简单的解决方案来满足用户需求,避免过度设计。
  13. ## UI和样式设计
  14. - 使用现代UI框架进行样式设计(例如 **React** 或 **Vue.js**,遵循 **Material Design** 或 **Chrome扩展设计规范**);
  15. - 在不同平台上实现一致的设计和响应式模式
  16. ## 代码编写
  17. - 技术选型:根据项目需求选择合适的技术栈(例如 **JavaScript** 用于主要开发语言,**HTML** 用于构建页面结构,**CSS** 用于样式设计,**Chrome Extensions API** 用于浏览器扩展功能,**Webpack** 用于模块打包)
  18. - **JavaScript**:用于主要开发语言,遵循面向对象编程原则,确保代码结构清晰。  
  19. - **HTML**:用于构建页面结构,遵循语义化标签原则,确保页面结构清晰。  
  20. - **CSS**:用于样式设计,遵循模块化样式原则,确保样式易于维护。  
  21. - **Chrome Extensions API**:用于浏览器扩展功能,遵循Chrome扩展开发规范,确保功能实现符合浏览器要求。  
  22. - **Webpack**:用于模块打包,遵循模块化开发原则,确保代码结构清晰且易于维护。
  23. - 代码结构:强调代码的清晰性、模块化、可维护性,遵循最佳实践(如DRY原则、最小权限原则、响应式设计等)
  24. - 代码安全性:在编写代码时,始终考虑安全性,避免引入漏洞,确保用户输入的安全处理- 性能优化:优化代码的性能,减少资源占用,提升加载速度,确保项目的高效运行
  25. ## 问题解决
  26. - 全面阅读相关代码,理解 **Chrome浏览器插件** 的工作原理- 根据用户的反馈分析问题的原因,提出解决问题的思路- 确保每次代码变更不会破坏现有功能,且尽可能保持最小的改动
  27. ## 迭代优化
  28. - 与用户保持密切沟通,根据反馈调整功能和设计,确保应用符合用户需求
  29. - 在不确定需求时,主动询问用户以澄清需求或技术细节- 每次迭代都需要更新README.md文件,包括功能说明和优化建议
  30. ## 方法论
  31. - 迭代改进:在最终确定代码之前,考虑改进、边缘情况和优化。通过潜在增强的迭代,确保最终解决方案是健壮的
复制代码
Project Rules

Project Rules提供了更一个强大且灵活的系统,具有路径特定的设置。全部Project rules都会存储在 .cursor/rules 目次中,可以实现对项目中差别部分 AI 举动的更细粒度的控制。
好比大家可以看下面这张图的两个例子:

一个Project Rules是用来控制Python文件的编写规则:
  1.   You are an expert in Python, FastAPI, and scalable API development.  Key Principles  - Write concise, technical responses with accurate Python examples.  - Use functional, declarative programming; avoid classes where possible.  - Prefer iteration and modularization over code duplication.  - Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).  - Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).  - Favor named exports for routes and utility functions.  - Use the Receive an Object, Return an Object (RORO) pattern.  Python/FastAPI  - Use def for pure functions and async def for asynchronous operations.  - Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.  - File structure: exported router, sub-routes, utilities, static content, types (models, schemas).  - Avoid unnecessary curly braces in conditional statements.  - For single-line statements in conditionals, omit curly braces.  - Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).  Error Handling and Validation  - Prioritize error handling and edge cases:  - Handle errors and edge cases at the beginning of functions.  - Use early returns for error conditions to avoid deeply nested if statements.  - Place the happy path last in the function for improved readability.  - Avoid unnecessary else statements; use the if-return pattern instead.  - Use guard clauses to handle preconditions and invalid states early.  - Implement proper error logging and user-friendly error messages.  - Use custom error types or error factories for consistent error handling.  Dependencies  - FastAPI  - Pydantic v2  - Async database libraries like asyncpg or aiomysql  - SQLAlchemy 2.0 (if using ORM features)  FastAPI-Specific Guidelines  - Use functional components (plain functions) and Pydantic models for input validation and response schemas.  - Use declarative route definitions with clear return type annotations.  - Use def for synchronous operations and async def for asynchronous ones.  - Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events.  - Use middleware for logging, error monitoring, and performance optimization.  - Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading.  - Use HTTPException for expected errors and model them as specific HTTP responses.  - Use middleware for handling unexpected errors, logging, and error monitoring.  - Use Pydantic's BaseModel for consistent input/output validation and response schemas.  Performance Optimization  - Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.  - Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.  - Optimize data serialization and deserialization with Pydantic.  - Use lazy loading techniques for large datasets and substantial API responses.  Key Conventions  1. Rely on FastAPI’s dependency injection system for managing state and shared resources.  2. Prioritize API performance metrics (response time, latency, throughput).  3. Limit blocking operations in routes:     - Favor asynchronous and non-blocking flows.     - Use dedicated async functions for database and external API operations.     - Structure routes and dependencies clearly to optimize readability and maintainability. Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
复制代码
一个Project Rules是用来控制UI的编写规则:
  1.     You are an expert in UI and UX design principles for software development.    Visual Design    - Establish a clear visual hierarchy to guide user attention.    - Choose a cohesive color palette that reflects the brand (ask the user for guidelines).    - Use typography effectively for readability and emphasis.    - Maintain sufficient contrast for legibility (WCAG 2.1 AA standard).    - Design with a consistent style across the application.    Interaction Design    - Create intuitive navigation patterns.    - Use familiar UI components to reduce cognitive load.    - Provide clear calls-to-action to guide user behavior.    - Implement responsive design for cross-device compatibility.    - Use animations judiciously to enhance user experience.    Accessibility    - Follow WCAG guidelines for web accessibility.    - Use semantic HTML to enhance screen reader compatibility.    - Provide alternative text for images and non-text content.    - Ensure keyboard navigability for all interactive elements.    - Test with various assistive technologies.    Performance Optimization    - Optimize images and assets to minimize load times.    - Implement lazy loading for non-critical resources.    - Use code splitting to improve initial load performance.    - Monitor and optimize Core Web Vitals (LCP, FID, CLS).    User Feedback    - Incorporate clear feedback mechanisms for user actions.    - Use loading indicators for asynchronous operations.    - Provide clear error messages and recovery options.    - Implement analytics to track user behavior and pain points.    Information Architecture    - Organize content logically to facilitate easy access.    - Use clear labeling and categorization for navigation.    - Implement effective search functionality.    - Create a sitemap to visualize overall structure.    Mobile-First Design    - Design for mobile devices first, then scale up.    - Use touch-friendly interface elements.    - Implement gestures for common actions (swipe, pinch-to-zoom).    - Consider thumb zones for important interactive elements.    Consistency    - Develop and adhere to a design system.    - Use consistent terminology throughout the interface.    - Maintain consistent positioning of recurring elements.    - Ensure visual consistency across different sections.    Testing and Iteration    - Conduct A/B testing for critical design decisions.    - Use heatmaps and session recordings to analyze user behavior.    - Regularly gather and incorporate user feedback.    - Continuously iterate on designs based on data and feedback.    Documentation    - Maintain a comprehensive style guide.    - Document design patterns and component usage.    - Create user flow diagrams for complex interactions.    - Keep design assets organized and accessible to the team.    Fluid Layouts    - Use relative units (%, em, rem) instead of fixed pixels.    - Implement CSS Grid and Flexbox for flexible layouts.    - Design with a mobile-first approach, then scale up.    Media Queries    - Use breakpoints to adjust layouts for different screen sizes.    - Focus on content needs rather than specific devices.    - Test designs across a range of devices and orientations.    Images and Media    - Use responsive images with srcset and sizes attributes.    - Implement lazy loading for images and videos.    - Use CSS to make embedded media (like iframes) responsive.    Typography    - Use relative units (em, rem) for font sizes.    - Adjust line heights and letter spacing for readability on small screens.    - Implement a modular scale for consistent typography across breakpoints.    Touch Targets    - Ensure interactive elements are large enough for touch (min 44x44 pixels).    - Provide adequate spacing between touch targets.    - Consider hover states for desktop and focus states for touch/keyboard.    Performance    - Optimize assets for faster loading on mobile networks.    - Use CSS animations instead of JavaScript when possible.    - Implement critical CSS for above-the-fold content.    Content Prioritization    - Prioritize content display for mobile views.    - Use progressive disclosure to reveal content as needed.    - Implement off-canvas patterns for secondary content on small screens.    Navigation    - Design mobile-friendly navigation patterns (e.g., hamburger menu).    - Ensure navigation is accessible via keyboard and screen readers.    - Consider using a sticky header for easy navigation access.    Forms    - Design form layouts that adapt to different screen sizes.    - Use appropriate input types for better mobile experiences.    - Implement inline validation and clear error messaging.    Testing    - Use browser developer tools to test responsiveness.    - Test on actual devices, not just emulators.    - Conduct usability testing across different device types.    Stay updated with the latest responsive design techniques and browser capabilities.    Refer to industry-standard guidelines and stay updated with latest UI/UX trends and best practices.
复制代码
每一条规则,你都可以写得非常详尽。
接下来先容怎么创建并利用一条Project Rules:
创建Project的方法有两种,一种是在【Cursor Settings-Rules-Project Rules】中点击【+Add new rules】;

一种是用快捷键 Cmd + Shift + P 调起下令面板,然后搜索 New Cursor Rule 进行创建;

两种方法都会先打开这么一个【Enter Rule Name】的窗口,就是给Project Rules定名,定名没啥硬性规则,自己怎么方便怎么来,究竟最后都是为自己服务的。
定名完成后,就会睁开这样一个界面,有三部分必要我们设置:

Description:用来形貌什么时候用这条Project Rules,不用写很复杂,简洁清晰即可,因为它是写给Agent看的。
在Cursor的Agent模式下,Agent可以看到这条形貌,并根据使命需求,决定是否阅读完整的Project Rules;
Auto Attach(有一些版本大概还是Globs):它能实现的能力,简单来说就是文件类型匹配,能将这条指定规则应用到特定的文件/文件夹。
好比前面那条Python编写规则,大家可以在Auto Attach中填写.py,那这些编写规则就可以适用于全部Python文件;
不但云云,Auto Attach还可以指定特定路径的文件。
两种方式,都是帮助我们更精准地锁定目标文件。
假如没有添加Description大概Auto Attach的话会怎样?大家可以看下面这张图中两处有报黄提醒的两个Project Rules,一条是没有添加Descripiton,一条是没有添加Auto Attach。
因此它们在Agent模式下也不会被应用

Rule Content
这部分其实就是.cursorrules分模块后的内容,有一个网址里面有一些不错的rules,地址:https://cursor.directory/rules
根本一个卡片就是一个Project Rules。

值得一提的是,在Rule Content中,是可以通过现有上下文引用(即@) 来添加附件的,这样你@的内容就会成为这条项目规则的一部分
利用Project Rules的方法也很简单,和之前先容的@file 的方式是一样的,因为Project Rules就是一个具体文件,支持将多个Project Rules串联起来利用

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

星球的眼睛

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表