Awesome Cursor Rules Collection

Showing 2125-2136 of 2626 matches

TypeScript
This works like this

./web - nextjs app router includes everything to related to user accounts 
./web/app/api/(new-ai) containts all the ai related functions
./plugin - obsidian plugin 



in the ./plugin use this values inside of tailwind classes like so

example:
text[--text-error]


- three plans
  - self-hosted (no license key)
  - lifetime (license key that also acts as api key with selfhostingurl)
  - subscription (license key that also acts as api key)



here's the list of variables you can use:
    --accent-h: 258;
    --accent-s: 88%;
    --accent-l: 66%;
    --background-primary: var(--color-base-00);
    --background-primary-alt: var(--color-base-10);
    --background-secondary: var(--color-base-20);
    --background-modifier-hover: rgba(var(--mono-rgb-100), 0.075);
    --background-modifier-active-hover: hsla(var(--interactive-accent-hsl), 0.15);
    --background-modifier-border: var(--color-base-30);
    --background-modifier-border-hover: var(--color-base-35);
    --background-modifier-border-focus: var(--color-base-40);
    --background-modifier-error-rgb: var(--color-red-rgb);
    --background-modifier-error: var(--color-red);
    --background-modifier-error-hover: var(--color-red);
    --background-modifier-success-rgb: var(--color-green-rgb);
    --background-modifier-success: var(--color-green);
    --background-modifier-message: rgba(0, 0, 0, 0.9);
    --background-modifier-form-field: var(--color-base-00);
    --text-normal: var(--color-base-100);
    --text-muted: var(--color-base-70);
    --text-faint: var(--color-base-50);
    --text-on-accent: white;
    --text-on-accent-inverted: black;
    --text-error: var(--color-red);
    --text-warning: var(--color-orange);
    --text-success: var(--color-green);
    --text-selection: hsla(var(--color-accent-hsl), 0.2);
    --text-highlight-bg-rgb: 255, 208, 0;
    --text-highlight-bg: rgba(var(--text-highlight-bg-rgb), 0.4);
    --text-accent: var(--color-accent);
    --text-accent-hover: var(--color-accent-2);
    --interactive-normal: var(--color-base-00);
    --interactive-hover: var(--color-base-10);
    --interactive-accent-hsl: var(--color-accent-hsl);
    --interactive-accent: var(--color-accent-1);
    --interactive-accent-hover: var(--color-accent-2);




	•	Access to shadcn/ui components library.
	•	Prioritize: Ease of Use > Aesthetics > Performance.
	•	Use Tailwind CSS for utility-first styling.

Recommended Libraries and Tools:

	1.	State Management:
	•	React Context API for simple state needs.
	•	Zustand for lightweight and scalable state management compatible with React Server Components.
	2.	Form Handling:
	•	React Hook Form for performant and flexible form management with easy validation.
	3.	Data Fetching:
	•	TanStack Query (formerly React Query) for efficient data fetching with caching and revalidation.
	4.	Authentication:
	•	Implement authentication using Clerk.
	5.	Animations:
	•	Framer Motion for smooth animations and transitions.
	6.	Icons:
	•	Use Lucide React for a collection of beautiful open-source icons.

AI Integration with Vercel AI SDK:

	•	Utilize the Vercel AI SDK, a TypeScript toolkit for building AI-powered applications with frameworks like React and Next.js.
	•	Implement conversational UIs using the useChat hook, which manages chat states and streams AI responses.

Using Tools with useChat and streamText:

	•	Types of Tools:
	•	Automatically executed server-side tools.
	•	Automatically executed client-side tools.
	•	User-interactive tools requiring confirmation dialogs.
	•	Workflow:
	1.	User inputs a message in the chat UI.
	2.	Message is sent to the API route.
	3.	Language model generates tool calls via streamText.
	4.	Tool calls are forwarded to the client.
	5.	Server-side tools execute and return results to the client.
	6.	Client-side tools auto-execute using the onToolCall callback.
	7.	Interactive tools display in the UI, results managed via toolInvocations.
	8.	After interactions, use addToolResult to include the result in the chat.
	9.	If tool calls exist in the last message and all results are available, the client resends messages to the server for further processing.
	•	Note: Set maxSteps to a value greater than 1 in useChat options to enable multiple iterations (default is disabled for compatibility).

Example Implementation:

	•	API Route (app/api/chat/route.ts):

import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
import { z } from 'zod';

// Allow streaming responses up to 30 seconds
export const maxDuration = 30;

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = await streamText({
    model: openai('gpt-4o'),
    messages,
    tools: {
      // Server-side tool with execute function:
      getWeatherInformation: {
        description: 'Show the weather in a given city to the user.',
        parameters: z.object({ city: z.string() }),
        execute: async ({ city }: { city: string }) => {
          const weatherOptions = ['sunny', 'cloudy', 'rainy', 'snowy', 'windy'];
          return `${city} is currently ${weatherOptions[Math.floor(Math.random() * weatherOptions.length)]}.`;
        },
      },
      // Client-side tool initiating user interaction:
      askForConfirmation: {
        description: 'Ask the user for confirmation.',
        parameters: z.object({
          message: z.string().describe('The message to ask for confirmation.'),
        }),
      },
      // Automatically executed client-side tool:
      getLocation: {
        description: 'Get the user location after confirmation.',
        parameters: z.object({}),
      },
    },
  });

  return result.toDataStreamResponse();
}


	•	Client-Side Page (app/page.tsx):

'use client';

import { ToolInvocation } from 'ai';
import { Message, useChat } from 'ai/react';
import { pipeline } from 'stream'
import { PlaySquareIcon } from 'lucide-react'

export default function Chat() {
  const {
    messages,
    input,
    handleInputChange,
    handleSubmit,
    addToolResult,
  } = useChat({
    maxSteps: 5,

    // Handle automatically executed client-side tools:
    async onToolCall({ toolCall }) {
      if (toolCall.toolName === 'getLocation') {
        const cities = ['New York', 'Los Angeles', 'Chicago', 'San Francisco'];
        return {
          city: cities[Math.floor(Math.random() * cities.length)],
        };
      }
    },
  });

  return (
    <>
      {messages?.map((m: Message) => (
        <div key={m.id}>
          <strong>{m.role}:</strong> {m.content}
          {m.toolInvocations?.map((toolInvocation: ToolInvocation) => {
            const toolCallId = toolInvocation.toolCallId;
            const addResult = (result: string) =>
              addToolResult({ toolCallId, result });

            // Render confirmation tool (client-side with user interaction)
            if (toolInvocation.toolName === 'askForConfirmation') {
              return (
                <div key={toolCallId}>
                  {toolInvocation.args.message}
                  <div>
                    {'result' in toolInvocation ? (
                      <b>{toolInvocation.result}</b>
                    ) : (
                      <>
                        <button onClick={() => addResult('Yes')}>Yes</button>
                        <button onClick={() => addResult('No')}>No</button>
                      </>
                    )}
                  </div>
                </div>
              );
            }

            // Display results of other tools
            return 'result' in toolInvocation ? (
              <div key={toolCallId}>
                <em>Tool ({toolInvocation.toolName}):</em> {toolInvocation.result}
              </div>
            ) : (
              <div key={toolCallId}>
                <em>Executing {toolInvocation.toolName}...</em>
              </div>
            );
          })}
          <br />
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} placeholder="Type your message..." />
      </form>
    </>
  );
}



Additional Notes:

	•	Ensure all tool invocations are properly managed to maintain a seamless user experience.
	•	Regularly update dependencies and libraries to their latest versions for improved performance and security.
	•	Test the chatbot thoroughly to handle edge cases and unexpected user inputs.

This revised prompt organizes the information more clearly, making it easier to understand and follow. It highlights key project guidelines, structures, and code examples, providing a comprehensive overview for anyone involved in the development process.


## pipeline

We have an inbox that processes files. 

The process happens in these steps:
- preprocess : trim content  | check if we support file type | check if we have a license
- extract (ai): extract text from file, we have a function in the plugin/index.ts for that
- classify (ai): classify the file, we have a function in the plugin/index.ts for that
- tag (ai): tag the file, we have a function in the plugin/index.ts for that
- format (ai): format the file, we have a function in the plugin/index.ts for that
- move: move the file to the correct folder, we have a function in the plugin/index.ts for that


each step should be logged in the record manager, and we should record the start and end of each step. 

all the ai steps are two folds one api call to get the llm recommendations
and one call to apply the recommendation. add tag after tagging , move file after folder recommendation, rename file after naming

when you classify apply a tag to the document there's append tag funciton on plugin 
only format if 1. there's a classification 2. there's no tag with the classification presetn

clerk
css
dockerfile
golang
javascript
less
next.js
openai
+6 more
Brandon-Baz/Obsidian-Concierge

Used in 1 repository

TypeScript
TypeScript
Chat style:

- Act as a mentor, reasoning about the best practices and patterns to use in the project.

Code style:

- Use functional and declarative programming patterns over imperative patterns and OOP.
- For components, use function expressions over function declarations.
- Favor pure functions over impure functions.

Naming conventions:

- For components, use PascalCase.
- For functions, use camelCase.
- For variables, use camelCase.
- Do NOT use kebab-case for anything. Never.

Architecture:

- Favor clean architecture and domain driven design.
- Favor common design patterns that make the code easier to understand, maintain and scale.

Releases:

- Use semantic-release to manage the release process.
- Commit messages should follow the conventional commits specification.
- That is: type(scope?): description

# ABOUT THE PROJECT

# Prisma Hono Generator

## Overview

A Prisma generator for Nextjs that automatically creates type-safe Hono API routes from Prisma schema models, providing seamless integration between your database schema and API endpoints.

## Core Features

### Route Generation

- ✨ Generates complete CRUD routes for each Prisma model
- 🔒 Type-safe request/response handling using Zod schemas
- 🚦 Proper HTTP methods mapping (GET, POST, PUT, DELETE)
- ✅ Automatic parameter validation
- 🔍 Query parameter support for filtering and pagination

### Type Safety

- 🛡️ Leverages Zod for runtime validation
- 🔄 Uses generated Prisma types
- ⚠️ Proper error handling with type information
- 📝 Type-safe request bodies and responses

### Generated Code Features

- 🏗️ Clean code structure with consistent patterns
- 📚 Comprehensive comments and documentation
- 🚨 Robust error handling
- ⚡ Validation middleware
- 🔎 Query parameter parsing
- 📦 Response formatting
- 📘 Swagger/OpenAPI documentation generation

### Integration Features

- ⚡ Works with Vercel/Edge functions
- 🔄 Compatible with Next.js App Router
- 🔌 Support for custom middleware
- ✨ Support for custom validation rules
- 🛠️ Support for custom error handling

## Technical Stack

### Dependencies

- `prisma` (peer dependency)
- `hono`
- `zod`
- `@prisma/generator-helper`
- `ts-morph` for code manipulation and generation
- `zod-prisma-types` for generating Zod schemas from Prisma models
- `@prisma/client` for database operations
- `tsup` for building the project

### Development Environment

- TypeScript
- Vitest for testing
- ESLint + Prettier
- GitHub Actions for CI/CD

## Project Structure

prisma-generator-hono/
├── src/
│ ├── generator/
│ ├── templates/
│ └── utils/
├── examples/
│ ├── basic/
│ └── advanced/
├── tests/
├── docs/
├── package.json
└── README.md

## Error Handling

- 🔄 Prisma errors mapping to HTTP status codes
- ⚠️ Validation error formatting
- 📝 Custom error responses
- 🛡️ Type-safe error handling

## Documentation

- 📚 README with comprehensive examples
- 📘 API documentation
- 🔧 Configuration guide
- 👥 Contributing guide
- 🔄 Migration guide
- ❓ Troubleshooting guide

## Development Roadmap

### Phase 1: Core Functionality

- [ ] Basic CRUD route generation
- [ ] Basic validation
- [ ] Error handling
- [ ] Simple configuration

### Phase 2: Enhanced Features

- [ ] Swagger documentation
- [ ] Advanced filtering
- [ ] Relationship handling
- [ ] Custom validation rules

### Phase 3: Advanced Features

- [ ] Custom middleware support
- [ ] Advanced configuration options
- [ ] Performance optimizations
- [ ] Edge function support

### Phase 4: Documentation & Polish

- [ ] Complete documentation
- [ ] Examples
- [ ] Testing
- [ ] CI/CD setup

## Target Users

- Next.js developers
- Prisma users
- TypeScript developers
- API developers prioritizing type safety
- Developers working with edge functions

## Development Workflow

1. Write code in `src/`
2. Test with `examples/basic`
3. Run tests with `npm test`
4. Publish when ready

---
eslint
express.js
javascript
less
next.js
npm
prettier
prisma
+4 more
RicSala/prisma-hono-generator

Used in 1 repository

JavaScript
Always respond in Türkçe
Bu proje bir iOS uygulamasının backendi olacaktır. Backend'de ExpressJS ve MongoDB kullanıyoruz. Kullanıcı girişi SMS ile yapılacaktır. Uygulama bir mesajlaşma uygulaması olacak. Uygulamada mesajlar bluetooth üzerinden yapılacak. İnternet erişimi olmadığında da kullanıcıların mesajlaşabilmesini istiyoruz ancak internet erişiminin sağlandığı zamanlarda uygulamadaki yerel veri tabanına kaydedilen verilen backend'e gönderilecektir. Şimdi de mesajlaşma işlemleri için gerekli olan senaryoları seninle paylaşmak istiyorum. Kullanıcıların 3 tane rolü olabiliyor; admin, guide(rehber) ve user. Rehber veya admin olmayan kullanıcı bir grup oluşturamaz ve kullanıcılar kendi aralarında mesajlaşamaz. Yalnızca grup üzerinden mesajlaşma olacak. Yani şu şekilde olacak. Bir kullanıcı mesajlaşmak için rehberlerin oluşturduğu bir gruba rehberin daveti ile katılmış olmalı ve yalnızca gruba mesaj gönderebilmeli. Bu konuda anlaştık diye düşünüyorum. Rehberden kastım şu, bu uygulama turistik gezilerde turist kafilesi ile rehber arasında özel bir mesajlaşma uygulaması olacak. Yani istediğimiz kullanıcılar arası özel bir mesajlaşma değil. Rehber mesajlaşma grubu oluşturacak, kullanıcıları davet edecek, kullanıcılar yalnızca grup içinde mesajlaşabilecek.
Backendi geliştirirken frontendciler için /docs klasörü altında dokümanlar oluşturuyoruz. Tüm yazılım ekibi öğrenci olduğu için dokümanlar ne kadar ayrıntılı, eksiksiz ve kaliteli olursa bizim için o kadar iyi olacaktır.
/routes kalsörü altındaki tüm Route'ların ve tüm endpointlerin API.md dosyasında olduğundan emin ol.
/models kalsörü altındaki tüm modellerin modellerin eksiksiz bir şekilde MODELS.md dosyasında olduğundan emin ol.
/routes klasörü altındaki tüm enpointlerin eksiksiz yazıldığından emin ol.
/routes klasörü altındaki tüm endpoinlerin yukarıda anlattığım senaryoya uygun olduğundan emin ol.
/routes klasörü altındaki tüm endpoinlerin swaggerUI kodlarının tam olduğundan emin ol.
yapılan her düzenlemeden sonra /docs klasörü altındaki dokümanlara eklememiz gereken veya düzenlememiz gereken bir şey olup olmadığından emin ol.
/docs klasörü altındaki API.md dosyası bizim için tek başına bir API dokümanı gibi olmalıdır. Yani içinde endpointler ve bu enpointlere nasıl istek yapılacağı hakkında detaylı bilgi mutlaka olmalıdır.
/docs kalsörü altındaki IOS_INTEGRATION.md dokümanına da iOS geliştiriciler için ayrıntılı bir doküman olması gerekiyor. Bu dokümanın da her zaman güncel ve diğer dosyalarla çakışmadığından emin ol.
Eklenen tüm kodlar için MongoDB'de yapılması gereken işlemler varsa bunları bana ayrıntılı bir şekilde söyle.
Admin panelini geliştirirken projenin genel yapısını bozmamaya dikkat et.
Admin paneli için gerekli tüm adımları ekleteceğiz, aşağıda admin paneli için gerekli olan özellikleri ve adımları listeledim;
    Mevcut durumda admin panelinde şu özellikler bulunuyor:
        Kullanıcı listesi görüntüleme
        Kullanıcı durumu güncelleme (aktif/bloke)
        Rehber listesi görüntüleme
        Rehber durumu güncelleme

    İstenen özelliklere göre eksik olan kısımları şöyle listeleyebiliriz:
        Kullanıcı Yönetimi için Eklenecekler:
        Kullanıcı arama ve filtreleme özellikleri
        Detaylı kullanıcı bilgisi görüntüleme endpoint'i
        Kullanıcı rolü değiştirme endpoint'i
        Kullanıcı istatistikleri endpoint'i
    Rehber Yönetimi için Eklenecekler:
        Rehber onaylama sistemi endpoint'leri
        Rehber performans istatistikleri endpoint'i
        Rehberlerin gruplarını görüntüleme endpoint'i
        Rehber raporları endpoint'i
    Grup Yönetimi için Eklenecekler:
        Tüm grupları listeleme ve filtreleme endpoint'i
        Grup detayları endpoint'i
        Grup durumu değiştirme endpoint'i
        Grup üye yönetimi endpoint'leri
        Grup istatistikleri endpoint'i
    İstatistikler ve Raporlama için Eklenecekler:
        Genel sistem istatistikleri endpoint'i
        Kullanıcı aktivite raporları endpoint'i
        Grup aktivite raporları endpoint'i
        Mesaj istatistikleri endpoint'i
        Dönemsel raporlar endpoint'i
    5. Sistem Yönetimi için Eklenecekler:
        Sistem durumu izleme endpoint'i
        Hata logları görüntüleme endpoint'i
        Performans metrikleri endpoint'i
        Bildirim yönetimi endpoint'leri
        Sistem ayarları endpoint'leri
    İmplementasyon Planımız bu şekilde olacak:
        Öncelikli Geliştirmeler (1. Faz):
            Kullanıcı yönetimi endpoint'lerinin tamamlanması
            Rehber onaylama sisteminin kurulması
            Temel grup yönetimi endpoint'lerinin eklenmesi
        İkincil Geliştirmeler (2. Faz):
            İstatistik ve raporlama altyapısının kurulması
            Performans metriklerinin eklenmesi
            Bildirim sisteminin entegrasyonu
        Son Faz (3. Faz):
            Sistem yönetimi özelliklerinin eklenmesi
            Detaylı raporlama özelliklerinin eklenmesi
            Hata izleme ve loglama sisteminin geliştirilmesi
    Her bir endpoint için şunları yapmalıyız:
        Route tanımlaması
        Swagger dokümantasyonu
        Gerekli middleware'lerin eklenmesi
        Error handling
        API.md ve IOS_INTEGRATION.md dokümanlarının güncellenmesi

    Admin paneline ekleyeceğimiz her bir özellik için detaylı implementasyon planı çıkar.
bun
express.js
golang
javascript
mongodb
vite

First seen in:

ihoflaz/backend-sara

Used in 1 repository

Jupyter Notebook
You are an expert in data analysis, visualization, and Jupyter Notebook development, with a focus on Python libraries such as pandas, matplotlib, seaborn, numpy, nibabel, SimpleITK, totalsegmentator, and other image processing tools.

Key Principles:

Write concise, technical responses with accurate Python examples.
Prioritize readability and reproducibility in data analysis workflows.
Use functional programming where appropriate; avoid unnecessary classes.
Prefer vectorized operations over explicit loops for better performance.
Use descriptive variable names that reflect the data they contain.
Follow PEP 8 style guidelines for Python code.

Data Analysis and Manipulation:

Use pandas and numpy for data manipulation and analysis.
Use nibabel and SimpleITK for handling medical imaging data.
Use totalsegmentator for automated segmentation tasks.
Prefer method chaining for data transformations when possible.
Use loc and iloc for explicit data selection in pandas DataFrames.
Utilize groupby operations for efficient data aggregation.
Leverage functions from image_utils for image processing tasks like converting series to NIfTI format and quantizing maps.

Visualization:

Use matplotlib for low-level plotting control and customization.
Use seaborn for statistical visualizations with aesthetically pleasing defaults.
Create informative and visually appealing plots with proper labels, titles, and legends.
Use appropriate color schemes and consider color-blindness accessibility.
Visualize medical imaging data using matplotlib and other specialized libraries.

Jupyter Notebook Best Practices:

Structure notebooks with clear sections using markdown cells.
Use meaningful cell execution order to ensure reproducibility.
Include explanatory text in markdown cells to document analysis steps.
Keep code cells focused and modular for easier understanding and debugging.
Use magic commands like %matplotlib inline for inline plotting.
Incorporate tqdm.notebook for progress bars within notebooks.

Error Handling and Data Validation:

Implement data quality checks at the beginning of the analysis.
Handle missing data appropriately through imputation, removal, or flagging.
Use try-except blocks for error-prone operations, especially when reading external data or processing images.
Validate data types and ranges to ensure data integrity.
Use logging to record errors and important events during execution.

Performance Optimization:

Use vectorized operations in pandas and numpy for improved performance.
Utilize efficient data structures, such as categorical data types for low-cardinality string columns.
Consider using Dask for larger-than-memory datasets.
Profile code to identify and optimize bottlenecks.
Optimize image processing workflows to handle large medical imaging datasets efficiently.

Dependencies:

pandas
numpy
matplotlib
seaborn
jupyter
scikit-learn (for machine learning tasks)
nibabel
SimpleITK
totalsegmentator
os (for file and directory operations)
tqdm.notebook (for progress bars)
logging
skimage.restoration (e.g., inpaint function)
image_utils (custom utilities like convert_series_to_nifti, quantize_maps, etc.)

Key Conventions:

Begin analysis with data exploration and summary statistics.
Create reusable functions for consistent data processing and visualizations.
Document data sources, assumptions, and methodologies clearly.
Use version control, such as git, for tracking changes in notebooks and scripts.

Refer to the official documentation of pandas, matplotlib, seaborn, numpy, nibabel, SimpleITK, totalsegmentator, and Jupyter for best practices and up-to-date APIs.
golang
jupyter notebook
python
rest-api
nicholasjprimianomd/CTH_CTA_CTP

Used in 1 repository

unknown
<!DOCTYPE html>
<html data-color-mode="light" data-dark-theme="dark_colorblind" data-light-theme="light" lang="zh-CN">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link href='https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/Primer/21.0.7/primer.css' rel='stylesheet' />
    <script src='https://blog.meekdai.com/Gmeek/plugins/GmeekVercount.js'></script>
    <link rel="icon" href="https://github.githubassets.com/favicons/favicon.svg"><script>
        let theme = localStorage.getItem("meek_theme") || "light";
        document.documentElement.setAttribute("data-color-mode", theme);
    </script>
<meta name="description" content="`.cursorrules` 是一个存放在项目根目录的特殊文件,用于自定义 Cursor 中的 AI 辅助规则。">
<meta property="og:title" content="cursorrules 终极指南:教你如何创建最优的 .cursorrules 文件">
<meta property="og:description" content="`.cursorrules` 是一个存放在项目根目录的特殊文件,用于自定义 Cursor 中的 AI 辅助规则。">
<meta property="og:type" content="article">
<meta property="og:url" content="https://haizhilingyu.github.io/post/cursorrules%20-zhong-ji-zhi-nan-%EF%BC%9A-jiao-ni-ru-he-chuang-jian-zui-you-de-%20.cursorrules%20-wen-jian.html">
<meta property="og:image" content="https://github.githubassets.com/favicons/favicon.svg">
<title>cursorrules 终极指南:教你如何创建最优的 .cursorrules 文件</title>
<link href="//unpkg.com/@wooorm/starry-night@2.1.1/style/both.css" rel="stylesheet" />


</head>
<style>
body{box-sizing: border-box;min-width: 200px;max-width: 900px;margin: 20px auto;padding: 45px;font-size: 16px;font-family: sans-serif;line-height: 1.25;}
#header{display:flex;padding-bottom:8px;border-bottom: 1px solid var(--borderColor-muted, var(--color-border-muted));margin-bottom: 16px;}
#footer {margin-top:64px; text-align: center;font-size: small;}

</style>

<style>
.postTitle{margin: auto 0;font-size:40px;font-weight:bold;}
.title-right{display:flex;margin:auto 0 0 auto;}
.title-right .circle{padding: 14px 16px;margin-right:8px;}
#postBody{border-bottom: 1px solid var(--color-border-default);padding-bottom:36px;}
#postBody hr{height:2px;}
#cmButton{height:48px;margin-top:48px;}
#comments{margin-top:64px;}
.g-emoji{font-size:24px;}
@media (max-width: 600px) {
    body {padding: 8px;}
    .postTitle{font-size:24px;}
}
.copy-feedback {
    display: none;
    position: absolute;
    top: 10px;
    right: 50px;
    color: var(--color-fg-on-emphasis);
    background-color: var(--color-fg-muted);
    border-radius: 3px;
    padding: 5px 8px;
    font-size: 12px;
}
</style>




<body>
    <div id="header">
<h1 class="postTitle">cursorrules 终极指南:教你如何创建最优的 .cursorrules 文件</h1>
<div class="title-right">
    <a href="https://haizhilingyu.github.io" id="buttonHome" class="btn btn-invisible circle" title="首页">
        <svg class="octicon" width="16" height="16">
            <path id="pathHome" fill-rule="evenodd"></path>
        </svg>
    </a>
    
    <a href="https://github.com/Haizhilingyu/haizhilingyu.github.io/issues/3" target="_blank" class="btn btn-invisible circle" title="Issue">
        <svg class="octicon" width="16" height="16">
            <path id="pathIssue" fill-rule="evenodd"></path>
        </svg>
    </a>
    

    <a class="btn btn-invisible circle" onclick="modeSwitch();" title="切换主题">
        <svg class="octicon" width="16" height="16" >
            <path id="themeSwitch" fill-rule="evenodd"></path>
        </svg>
    </a>

</div>
</div>
    <div id="content">
<div class="markdown-body" id="postBody"><p><code class="notranslate">.cursorrules</code> 是一个存放在项目根目录的特殊文件,用于自定义 Cursor 中的 AI 辅助规则。通过在这个文件中定义具体的规则,您可以为 AI 提供项目背景、编码标准、首选库、文件结构和性能指南等指示,从而使 AI 的代码生成和建议更加符合您的团队需求。</p>
<p>简单来说,<code class="notranslate">.cursorrules</code> 是您与 AI 之间的"沟通桥梁"。有了它,您不必每次都手动调整 AI 的行为,AI 将始终在您的项目需求范围内提供建议。</p>
<p><a target="_blank" rel="noopener noreferrer" href="https://github.com/user-attachments/assets/f90124e8-61d4-48cb-9fd8-c86f1c1967e0"><img src="https://github.com/user-attachments/assets/f90124e8-61d4-48cb-9fd8-c86f1c1967e0" alt="1fcb4f5670e8dfd016e383b80d7dea66md5" style="max-width: 100%;"></a></p>
<h2>如何为项目创建最佳的 .cursorrules?</h2>
<p>要充分利用 <code class="notranslate">.cursorrules</code> 文件,您需要将项目的各个关键部分清楚地传达给 AI。以下是一些创建高效 <code class="notranslate">.cursorrules</code> 文件的最佳做法:</p>
<h3><strong>1. 提供项目背景</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
AI 不了解项目的背景,而背景信息可以帮助 AI 理解项目的上下文,生成更合适的代码。</p>
</blockquote>
<p><strong>示例:</strong></p>
<div class="highlight highlight-text-md"><pre class="notranslate"><span class="pl-mh"># <span class="pl-en">项目背景 这是一个基于 Nextjs 的支持多语言的博客 Web 应用程序,使用 Nextjs 框架编写。</span></span></pre></div>
<p><strong>解释:</strong></p>
<p>在 <code class="notranslate">.cursorrules</code> 文件的开头,您可以提供一个简要的项目背景介绍。像“这是一个基于 Nextjs 的博客 Web 应用程序” 这样的描述可以让 AI 在生成代码时,选择适合的语法风格、文件类型和方法。</p>
<h3><strong>2. 定义编码标准</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
确保 AI 生成的代码符合团队的代码规范,避免不一致的编码风格。</p>
</blockquote>
<p><strong>示例:</strong></p>
<div class="highlight highlight-text-md"><pre class="notranslate"><span class="pl-mh"># <span class="pl-en">编码标准 - 使用函数式组件和 Hooks,避免类组件 - 变量声明优先使用 const,而不是 let - 变量和函数名使用 camelCase 规范,组件名使用 PascalCase</span></span></pre></div>
<p><strong>解释:</strong></p>
<p>这段代码告诉 AI,团队更喜欢函数式组件,而不是类组件。AI 还会优先使用 <code class="notranslate">const</code> 声明变量,并在函数和变量命名中遵循 camelCase 规范,而组件名称采用 PascalCase。</p>
<h3><strong>3. 指定首选的库和框架</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
如果 AI 不了解您首选的库,它可能会生成不适合的第三方依赖项。</p>
</blockquote>
<p><strong>示例:</strong></p>
<div class="highlight highlight-text-md"><pre class="notranslate"><span class="pl-mh"># <span class="pl-en">首选的库 - 使用 Next.js 进行导航 - 使用 next-intl 做国际化 - 使用 tailwind 进行 CSS-in-JS 样式设计</span></span></pre></div>
<p><strong>解释:</strong></p>
<p>这告诉 AI 在生成导航代码时优先使用 Next.js,而不是其他库(例如 React Router 路由系统)。对于样式,AI 会默认选择 <code class="notranslate">tailwind</code>,而不是 CSS 模块或其他 CSS 解决方案。</p>
<h3><strong>4. 提供文件结构信息</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
清晰的文件结构可帮助 AI 生成的文件路径和导入路径更准确,减少路径错误。</p>
</blockquote>
<p><strong>示例:</strong></p>
<pre lang="plaintext" class="notranslate"><code class="notranslate"># 文件结构 - components: 可复用的 UI 组件 - app/[locale]: 支持多语言的 nextjs 页面 - data/blog: 多语言的博客文件 - app/api: API 服务函数
</code></pre>
<p><strong>解释:</strong></p>
<p>告诉 AI 文件的目录结构有助于自动生成 <code class="notranslate">import</code> 路径。例如,当您要求 AI 创建一个新组件时,它会将其放入 <code class="notranslate">src/components</code> 目录,而不会错误地将其放入 <code class="notranslate">src/pages</code> 中。</p>
<h3><strong>5. 设置性能优化指南</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
如果您不告诉 AI 关注性能,它可能会生成不符合性能最佳实践的代码。</p>
</blockquote>
<p><strong>示例:</strong></p>
<div class="highlight highlight-text-md"><pre class="notranslate"><span class="pl-mh"># <span class="pl-en">性能优化指南 - 对纯函数组件使用 React.memo - 路由组件实现懒加载 - 优化 useEffect 依赖,防止不必要的重新渲染</span></span></pre></div>
<p><strong>解释:</strong></p>
<p>这些规则可帮助 AI 生成更高效的代码。例如,当 AI 生成 <code class="notranslate">useEffect</code> 钩子时,它会确保依赖项数组是完整的,从而防止不必要的重新渲染。</p>
<h3><strong>6. 设定测试要求</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
如果您有特定的测试需求,AI 可以帮助您自动生成符合这些标准的测试用例。</p>
</blockquote>
<p><strong>示例:</strong></p>
<pre lang="plaintext" class="notranslate"><code class="notranslate"># 测试要求 - 使用 Jest 和 React Testing Library 编写单元测试 - 测试覆盖率应至少达到 80% - 对 UI 组件使用快照测试 (Snapshot Testing)
</code></pre>
<p><strong>解释:</strong><br>
这段规则告诉 AI 在生成测试文件时使用 Jest 和 React Testing Library,还会自动生成快照测试 (Snapshot Testing) 以捕获 UI 变化。</p>
<h3><strong>7. 编写文档规范</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
规范的文档有助于团队协作,并确保 AI 生成的代码自带注释和解释。</p>
</blockquote>
<p><strong>示例:</strong></p>
<pre lang="plaintext" class="notranslate"><code class="notranslate"># 文档规范 - 使用 JSDoc 格式编写函数和组件的注释 - 组件必须包含 PropTypes 验证 - 每个主要目录必须包含 README.md 文件 - 同时提供英语和中文版本的 README.md 文件
</code></pre>
<p><strong>解释:</strong></p>
<p>使用 JSDoc 规则可确保 AI 自动生成的函数和组件包含函数定义、参数说明和返回类型的注释。</p>
<h3><strong>8. 设置错误处理偏好</strong></h3>
<blockquote>
<p><strong>为什么重要?</strong><br>
AI 可能不会自动考虑错误处理逻辑。</p>
</blockquote>
<p><strong>示例:</strong></p>
<div class="highlight highlight-text-md"><pre class="notranslate"><span class="pl-mh"># <span class="pl-en">错误处理 - 使用 try/catch 块处理异步操作 - 实现全局错误边界组件</span></span></pre></div>
<p><strong>解释:</strong></p>
<p>这些规则告诉 AI 在生成异步函数时,自动在内部使用 <code class="notranslate">try/catch</code> 块。AI 还可能在项目中实现一个全局的“错误边界”组件,以捕获运行时错误。</p>
<h2>如何在项目中使用 .cursorrules?</h2>
<ol>
<li><strong>创建文件:</strong> 在项目根目录创建 <code class="notranslate">.cursorrules</code> 文件。</li>
<li><strong>定义规则:</strong> 按照上文的建议,定义项目背景、编码标准和文件结构等规则。</li>
<li><strong>重启 Cursor:</strong> 在 Cursor 中,重启 AI 助手以加载新的 .cursorrules 文件。</li>
<li><strong>实时调整:</strong> 当项目需求发生变化时,及时更新 .cursorrules 文件。</li>
</ol>
<h2>如何利用“AI 规则”实现全局控制?</h2>
<p>除了项目的 <code class="notranslate">.cursorrules</code> 文件,您还可以在 Cursor 的“设置 &gt; 通用 &gt; AI 规则”中编写适用于所有项目的全局 AI 规则。这些规则将自动应用于每个项目,无需手动为每个项目创建 .cursorrules 文件。</p>
<h2>总结:您的 Cursor 从未如此聪明</h2>
<p>通过在项目中创建 <code class="notranslate">.cursorrules</code> 文件,您可以为 AI 提供清晰的指示,从而使 AI 生成的代码更符合您的项目需求。</p>
<p>有了这些技巧,您不仅可以加快开发速度,还能确保代码质量始终保持高标准。</p>
<p>希望这篇指南能帮助您充分发挥 Cursor 和 .cursorrules 的潜力!</p>
<p>原文地址:<a href="https://www.ifb.me/zh/blog/zh/ai/cursorrules-zhong-ji" rel="nofollow">https://www.ifb.me/zh/blog/zh/ai/cursorrules-zhong-ji</a></p></div>
<div style="font-size:small;margin-top:8px;float:right;"></div>

<button class="btn btn-block" type="button" onclick="openComments()" id="cmButton">评论</button>
<div class="comments" id="comments"></div>

</div>
    <div id="footer"><div id="footer1">Copyright © <span id="copyrightYear"></span> <a href="https://haizhilingyu.github.io">个人记录</a></div>
<div id="footer2">
    <span id="runday"></span><span>Powered by <a href="https://meekdai.com/Gmeek.html" target="_blank">Gmeek</a></span>
</div>

<script>
var now=new Date();
document.getElementById("copyrightYear").innerHTML=now.getFullYear();

if("12/16/2024"!=""){
    var startSite=new Date("12/16/2024");
    var diff=now.getTime()-startSite.getTime();
    var diffDay=Math.floor(diff/(1000*60*60*24));
    document.getElementById("runday").innerHTML="网站运行"+diffDay+"天"+" • ";
}
</script></div>
</body>
<script>
var IconList={'sun': 'M8 10.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5zM8 12a4 4 0 100-8 4 4 0 000 8zM8 0a.75.75 0 01.75.75v1.5a.75.75 0 01-1.5 0V.75A.75.75 0 018 0zm0 13a.75.75 0 01.75.75v1.5a.75.75 0 01-1.5 0v-1.5A.75.75 0 018 13zM2.343 2.343a.75.75 0 011.061 0l1.06 1.061a.75.75 0 01-1.06 1.06l-1.06-1.06a.75.75 0 010-1.06zm9.193 9.193a.75.75 0 011.06 0l1.061 1.06a.75.75 0 01-1.06 1.061l-1.061-1.06a.75.75 0 010-1.061zM16 8a.75.75 0 01-.75.75h-1.5a.75.75 0 010-1.5h1.5A.75.75 0 0116 8zM3 8a.75.75 0 01-.75.75H.75a.75.75 0 010-1.5h1.5A.75.75 0 013 8zm10.657-5.657a.75.75 0 010 1.061l-1.061 1.06a.75.75 0 11-1.06-1.06l1.06-1.06a.75.75 0 011.06 0zm-9.193 9.193a.75.75 0 010 1.06l-1.06 1.061a.75.75 0 11-1.061-1.06l1.06-1.061a.75.75 0 011.061 0z', 'moon': 'M9.598 1.591a.75.75 0 01.785-.175 7 7 0 11-8.967 8.967.75.75 0 01.961-.96 5.5 5.5 0 007.046-7.046.75.75 0 01.175-.786zm1.616 1.945a7 7 0 01-7.678 7.678 5.5 5.5 0 107.678-7.678z', 'sync': 'M1.705 8.005a.75.75 0 0 1 .834.656 5.5 5.5 0 0 0 9.592 2.97l-1.204-1.204a.25.25 0 0 1 .177-.427h3.646a.25.25 0 0 1 .25.25v3.646a.25.25 0 0 1-.427.177l-1.38-1.38A7.002 7.002 0 0 1 1.05 8.84a.75.75 0 0 1 .656-.834ZM8 2.5a5.487 5.487 0 0 0-4.131 1.869l1.204 1.204A.25.25 0 0 1 4.896 6H1.25A.25.25 0 0 1 1 5.75V2.104a.25.25 0 0 1 .427-.177l1.38 1.38A7.002 7.002 0 0 1 14.95 7.16a.75.75 0 0 1-1.49.178A5.5 5.5 0 0 0 8 2.5Z', 'home': 'M6.906.664a1.749 1.749 0 0 1 2.187 0l5.25 4.2c.415.332.657.835.657 1.367v7.019A1.75 1.75 0 0 1 13.25 15h-3.5a.75.75 0 0 1-.75-.75V9H7v5.25a.75.75 0 0 1-.75.75h-3.5A1.75 1.75 0 0 1 1 13.25V6.23c0-.531.242-1.034.657-1.366l5.25-4.2Zm1.25 1.171a.25.25 0 0 0-.312 0l-5.25 4.2a.25.25 0 0 0-.094.196v7.019c0 .138.112.25.25.25H5.5V8.25a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 .75.75v5.25h2.75a.25.25 0 0 0 .25-.25V6.23a.25.25 0 0 0-.094-.195Z', 'github': 'M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z', 'copy': 'M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z', 'check': 'M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z'};
var utterancesLoad=0;

let themeSettings={
    "dark": ["dark","moon","#00f0ff","dark-blue"],
    "light": ["light","sun","#ff5000","github-light"],
    "auto": ["auto","sync","","preferred-color-scheme"]
};
function changeTheme(mode, icon, color, utheme){
    document.documentElement.setAttribute("data-color-mode",mode);
    document.getElementById("themeSwitch").setAttribute("d",value=IconList[icon]);
    document.getElementById("themeSwitch").parentNode.style.color=color;
    if(utterancesLoad==1){utterancesTheme(utheme);}
}
function modeSwitch(){
    let currentMode=document.documentElement.getAttribute('data-color-mode');
    let newMode = currentMode === "light" ? "dark" : currentMode === "dark" ? "auto" : "light";
    localStorage.setItem("meek_theme", newMode);
    if(themeSettings[newMode]){
        changeTheme(...themeSettings[newMode]);
    }
}
function utterancesTheme(theme){
    const message={type:'set-theme',theme: theme};
    const iframe=document.getElementsByClassName('utterances-frame')[0];
    iframe.contentWindow.postMessage(message,'https://utteranc.es');
}
if(themeSettings[theme]){changeTheme(...themeSettings[theme]);}
console.log("\n %c Gmeek last https://github.com/Meekdai/Gmeek \n","padding:5px 0;background:#02d81d;color:#fff");
</script>

<script>
document.getElementById("pathHome").setAttribute("d",IconList["home"]);
document.getElementById("pathIssue").setAttribute("d",IconList["github"]);



function openComments(){
    cm=document.getElementById("comments");
    cmButton=document.getElementById("cmButton");
    cmButton.innerHTML="loading";
    span=document.createElement("span");
    span.setAttribute("class","AnimatedEllipsis");
    cmButton.appendChild(span);

    script=document.createElement("script");
    script.setAttribute("src","https://utteranc.es/client.js");
    script.setAttribute("repo","Haizhilingyu/haizhilingyu.github.io");
    script.setAttribute("issue-term","title");
    
    if(localStorage.getItem("meek_theme")=="dark"){script.setAttribute("theme","dark-blue");}
    else if(localStorage.getItem("meek_theme")=="light") {script.setAttribute("theme","github-light");}
    else{script.setAttribute("theme","preferred-color-scheme");}
    
    script.setAttribute("crossorigin","anonymous");
    script.setAttribute("async","");
    cm.appendChild(script);

    int=self.setInterval("iFrameLoading()",200);
}

function iFrameLoading(){
    var utterances=document.getElementsByClassName('utterances');
    if(utterances.length==1){
        if(utterances[0].style.height!=""){
            utterancesLoad=1;
            int=window.clearInterval(int);
            document.getElementById("cmButton").style.display="none";
            console.log("utterances Load OK");
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
    const createClipboardHTML = (codeContent, additionalClasses = '') => `
        <pre class="notranslate"><code class="notranslate">${codeContent}</code></pre>
        <div class="clipboard-container position-absolute right-0 top-0 ${additionalClasses}">
            <clipboard-copy class="ClipboardButton btn m-2 p-0" role="button" style="display: inherit;">
                <svg height="16" width="16" class="octicon octicon-copy m-2"><path d="${IconList["copy"]}"></path></svg>
                <svg height="16" width="16" class="octicon octicon-check color-fg-success m-2 d-none"><path d="${IconList["check"]}"></path></svg>
            </clipboard-copy>
            <div class="copy-feedback">Copied!</div>
        </div>
    `;

    const handleCodeElements = (selector = '') => {
        document.querySelectorAll(selector).forEach(codeElement => {
            const codeContent = codeElement.innerHTML;
            const newStructure = document.createElement('div');
            newStructure.className = 'snippet-clipboard-content position-relative overflow-auto';
            newStructure.innerHTML = createClipboardHTML(codeContent);

            const parentElement = codeElement.parentElement;
            if (selector.includes('highlight')) {
                parentElement.insertBefore(newStructure, codeElement.nextSibling);
                parentElement.removeChild(codeElement);
            } else {
                parentElement.parentElement.replaceChild(newStructure, parentElement);
            }
        });
    };

    handleCodeElements('pre.notranslate > code.notranslate');
    handleCodeElements('div.highlight > pre.notranslate');

    let currentFeedback = null;
    document.querySelectorAll('clipboard-copy').forEach(copyButton => {
        copyButton.addEventListener('click', () => {
            const codeContent = copyButton.closest('.snippet-clipboard-content').innerText;
            const tempTextArea = document.createElement('textarea');
            tempTextArea.value = codeContent;
            document.body.appendChild(tempTextArea);
            tempTextArea.select();
            document.execCommand('copy');
            document.body.removeChild(tempTextArea);

            const copyIcon = copyButton.querySelector('.octicon-copy');
            const checkIcon = copyButton.querySelector('.octicon-check');
            const copyFeedback = copyButton.nextElementSibling;

            if (currentFeedback && currentFeedback !== copyFeedback) {currentFeedback.style.display = 'none';}
            currentFeedback = copyFeedback;

            copyIcon.classList.add('d-none');
            checkIcon.classList.remove('d-none');
            copyFeedback.style.display = 'block';
            copyButton.style.borderColor = 'var(--color-success-fg)';

            setTimeout(() => {
                copyIcon.classList.remove('d-none');
                checkIcon.classList.add('d-none');
                copyFeedback.style.display = 'none';
                copyButton.style.borderColor = '';
            }, 2000);
        });
    });
});

</script>
<script src='https://blog.meekdai.com/Gmeek/plugins/GmeekTOC.js'></script><script src='https://blog.meekdai.com/Gmeek/plugins/lightbox.js'></script>

</html>
jest
next.js
react
solidjs
tailwindcss
Haizhilingyu/haizhilingyu.github.io

Used in 1 repository