Awesome Cursor Rules Collection

Showing 841-852 of 1033 matches

TypeScript
このリポジトリはプロジェクトのウィジェット機能とダッシュボードを提供するプロジェクトのウィジェット機能を提供しているリポジトリです。
以下のガイドラインに従って開発を進めてください:

1. 技術スタック:
  - ウィジェット:TypeScript、React、Vite、Web Components, 、Shadcn UI、Radix UI、Tailwind CSS, Supabaseを使用します。

2. コードスタイル:
  - 簡潔で技術的なTypeScriptコードを書き、正確な例を提供します。
  - 関数型と宣言型のプログラミングパターンを使用し、クラスは避けます(ウィジェットのWeb Components除く)。
  - 反復処理とモジュール化を優先し、コードの重複を避けます。
  - 説明的な変数名を使用し、補助動詞を含めます(例:isLoading、hasError)。
  - ファイル構造:エクスポートされるコンポーネント、サブコンポーネント、ヘルパー、静的コンテンツ、型の順に構成します。
  - forEach、for-ofループの代わりに、map、filter、find、reduceなどを使用します。

3. コメント:
  - コードの先頭にJSDocコメントを追加し、@fileを使用します。
  - スクリプトの概要、主な仕様、制限事項を小学生でも理解できるように記述します。
  - 複雑な処理がある場合は、処理の流れを説明します。重複を避け、@returns {JSX.Element}は記載しません。
  - @path,@expampleを記載します。

4. 命名規則:
  - ディレクトリ名は小文字とダッシュを使用します(例:components/auth-wizard)。
  - コンポーネントには名前付きエクスポートを使用します。

5. TypeScript:
  - すべてのコードでTypeScriptを使用し、型よりもインターフェースを優先します。
  - enumの代わりにマップを使用します。
  - TypeScriptインターフェースを持つ関数コンポーネントを使用します。

6. 構文とフォーマット:
  - 条件文では不要な中括弧を避け、簡潔な構文を使用します。
  - 宣言的なJSXを使用します。

7. UIとスタイリング:
  - Shadcn UI、Radix、Tailwindを使用します。
  - レスポンシブデザインを実装し、モバイルファーストアプローチを取ります。

8. パフォーマンス最適化:
  - ダッシュボード:
    - 'use client'、useEffect、setStateの使用を最小限に抑え、React Server Components(RSC)を優先します。
    - クライアントコンポーネントはSuspenseでラップし、フォールバックを提供します。
  - ウィジェット:
    - バンドルサイズを最小限に抑え、パフォーマンスを最適化します。
  - 共通:
    - 重要でないコンポーネントには動的ロードを使用します。
    - 画像最適化:WebP形式を使用し、サイズデータを含め、遅延ロードを実装します。

9. 主要な規約:
  - ダッシュボード:URL検索パラメータの状態管理には'nuqs'を使用します。
  - Web Vitals(LCP、CLS、FID)を最適化します。

10. アプリケーション開発ガイドライン:
    - Supabaseをデータベースとストレージ管理に使用し、認証には使用しません。
    - ウィジェット:React ViteでWeb Componentsを作成し、クラスベースアプローチとShadow DOMを採用します。
    - ダッシュボード:Next.jsのServer ComponentsとServer Actionsを実装してパフォーマンスを向上させます。
    - データフェッチとテーブル管理にはTanStack QueryとTanStack Tableを使用します。
    - クライアントとサーバー両側で適切なエラーハンドリングを行い、ユーザーフレンドリーなメッセージを提供します。
    - 最低限、英語と日本語の国際化(i18n)サポートを実装します。
    - ユーザーが複数のプロジェクトを作成、表示、管理できるプロジェクト管理システムを実装します。
    - 各プロジェクトに固有のウィジェットコードを生成し、外部サイトへの簡単な埋め込みを可能にします。
    - 環境変数を使用して機密情報とAPIキーを管理します。
    - 入力のサニタイズやContent Security Policy(CSP)など、適切なセキュリティ対策を実装します。
    - ダッシュボードとウィジェットコンポーネントの両方でレスプンシブデザインを確保します。
    - 認証フローを含む包括的なユニットテストと統合テストを作成します。
    - スケーラビリティと保守性を確保するためにモジュラーアーキテクチャを使用します。

これらのガイドラインは、プロジェクトの進化に合わせて定期的に見直し、更新してください。

ダッシュボードのデータフェッチ、レンダリング、ルーティングについては、Next.jsのドキュメントに従ってください。ウィジェットについては、React ViteとWeb Componentsのベストプラクティスに従ってください。
css
html
javascript
next.js
radix-ui
react
shadcn/ui
supabase
+3 more
chibataku0815/saas-widget

Used in 1 repository

TypeScript
You are an expert full-stack developer proficient in TypeScript, React, Next.js, and modern UI/UX frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI). Your task is to produce the most optimized and maintainable Next.js code, following best practices and adhering to the principles of clean code and robust architecture.

## Objective

- Create a Next.js solution that is not only functional but also adheres to the best practices in performance, security, and maintainability
- Ensure each tool component follows a standardized structure with proper documentation and user guides

## Code Style and Structure

- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Favor iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`)
- Structure files with exported components, subcomponents, helpers, static content, and types
- Use lowercase with dashes for directory names (e.g., `components/auth-wizard`)

### Tool Component Structure

```
components/tools/[tool-name]/
  ├── index.tsx           # Main tool component
  ├── guide-section.tsx   # Tool documentation and guides
  ├── schema.ts          # Zod validation schemas
  └── types.ts           # TypeScript definitions
```

## Optimization and Best Practices

- Minimize the use of `'use client'`, `useEffect`, and `setState`; favor React Server Components (RSC) and Next.js SSR features
- Use responsive design with a mobile-first approach
- Optimize images: use WebP format, include size data, implement lazy loading

### Standard Tool Layout

```typescript
<ToolLayout
  translationKey="tools.[tool-name]"
  guideSection={<GuideSection />}
>
  <MainTool />
</ToolLayout>
```

## Error Handling and Validation

- Prioritize error handling and edge cases:
  - Use early returns for error conditions
  - Implement guard clauses to handle preconditions and invalid states early
  - Use custom error types for consistent error handling

### Standard Error Class

```typescript
export class ToolError extends Error {
  constructor(
    message: string,
    public code: string,
    public context?: Record<string, any>
  ) {
    super(message);
    this.name = "ToolError";
  }
}
```

## UI and Styling

- Use modern UI frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI) for styling
- Implement consistent design and responsive patterns across platforms
- Structure guide sections with standardized tabs:
  - Usage guide
  - Features overview
  - Tips and best practices

## State Management and Data Fetching

- Use modern state management solutions (e.g., Zustand, TanStack React Query) to handle global state and data fetching
- Implement validation using Zod for schema validation

### Translation Structure

```json
{
  "tools": {
    "[tool-name]": {
      "title": "Tool Name",
      "guide": {
        "title": "Guide",
        "features": {
          "title": "Features"
        },
        "tips": {
          "title": "Tips & Tricks"
        }
      }
    }
  }
}
```

## Security and Performance

- Implement proper error handling, user input validation, and secure coding practices
- Follow performance optimization techniques, such as reducing load times and improving rendering efficiency
- Ensure each tool component implements proper input sanitization

## Testing and Documentation

- Write unit tests for components using Jest and React Testing Library
- Provide clear and concise comments for complex logic
- Use JSDoc comments for functions and components to improve IDE intellisense
- Include standardized guide sections for each tool with:
  - Usage examples
  - Feature documentation
  - Common pitfalls and solutions

## Methodology

### System 2 Thinking

Approach the problem with analytical rigor. Break down the requirements into smaller, manageable parts and thoroughly consider each step before implementation.

### Tree of Thoughts

Evaluate multiple possible solutions and their consequences. Use a structured approach to explore different paths and select the optimal one.

### Iterative Refinement

Before finalizing the code, consider improvements, edge cases, and optimizations. Iterate through potential enhancements to ensure the final solution is robust.

## Development Process

1. **Deep Dive Analysis**

   - Conduct thorough analysis of requirements
   - Consider technical constraints
   - Identify potential challenges

2. **Planning**

   - Develop architectural structure
   - Map out solution flow
   - Create component hierarchy

3. **Implementation**

   - Follow best practices
   - Implement step-by-step
   - Maintain code quality

4. **Review and Optimize**

   - Review code quality
   - Identify optimization opportunities
   - Refactor as needed

5. **Finalization**

   - Ensure requirements are met
   - Verify security measures
   - Check performance metrics

6. **Documentation**
   - Complete guide sections
   - Add usage documentation
   - Include code comments
css
dockerfile
golang
javascript
jest
next.js
radix-ui
react
+4 more

First seen in:

kelvin6365/rocksdev.tools

Used in 1 repository

unknown
// Project: Core Standards and Structure
// Description: Fundamental project configuration and organization

// Technology Stack
- Primary languages: TypeScript, Python
- Frontend: React with Next.js
- Backend: Node.js/Express, Python/FastAPI
- Database: PostgreSQL (primary), MongoDB (document store)
- Infrastructure: Kubernetes, AWS/Azure

// Core Standards
- Code Style:
  * TypeScript/JavaScript: 2 spaces, prettier config
  * Python: 4 spaces, black formatter
  * Maximum line length: 100 characters
- Naming:
  * TypeScript: camelCase variables, PascalCase classes
  * Python: snake_case variables, PascalCase classes
  * Constants: UPPER_SNAKE_CASE
  * Files: lowercase-with-dashes.ts

// Project Structure
/src
  /apps                    # Application code
    /web                   # Web frontend
    /api                   # API backend
    /admin                 # Admin interface
  /packages               # Shared packages
    /ui                   # UI components
    /utils               # Shared utilities
    /types              # TypeScript types
  /infrastructure        # IaC and deployment
    /kubernetes
    /terraform
    /scripts
  /docs                  # Documentation
    /architecture
    /api
    /deployment
  /tests                 # Test suites
    /unit
    /integration
    /e2e

// Core Architecture
- Frontend: 
  * Next.js pages and app router
  * Modular component architecture
  * State management with React Query
- Backend:
  * RESTful API with OpenAPI/Swagger
  * Domain-driven design principles
  * Repository pattern for data access
- Infrastructure:
  * Container-based deployment
  * GitOps-based workflows
  * Infrastructure as Code

// Development Flow
- Branch Strategy:
  * main: production-ready code
  * develop: integration branch
  * feature/*: new features
  * fix/*: bug fixes
- Commits:
  * Conventional commits format
  * Signed commits required
  * Linear history (rebase workflow)
- Reviews:
  * Required for all changes
  * Two approvals minimum
  * CI checks must pass 
aws
azure
express.js
fastapi
golang
java
javascript
kubernetes
+8 more
TMHSDigital/CursorRulesFiles

Used in 1 repository

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

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

TypeScript
# TypeScript and Next.js Development Guidelines

## Expert Role
You are an expert in TypeScript, Node.js, Next.js, App Router, React, Shadcn UI, Radix UI and Tailwind.

## Code Style and Structure
- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure files: exported component, subcomponents, helpers, static content, types

## Naming Conventions
- Use Lowercase with dashes for directories (e.g., components/auth-wizard)
- Favor named exports for components

## TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use maps instead
- Use functional components with TypeScript interfaces

## Syntax and Formatting
- Use the "function" keyword for pure functions
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
- Use declarative TSX

## UI and Styling
- Use Shadon UI, Radix, and Tailwind for components and styling
- Implement responsive design with Tailwind CSS; use a mobile-first approach

## Performance Optimization
- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC)
- Wrap client components in Suspense with fallback
- Use dynamic loading for non-critical components
- Optimize images: use WebP format, include size data, implement lazy loading

## Key Conventions
- Use 'nuqs' for URL search parameter state management
- Optimize Web Vitals (LCP, CLS, FID)
- Limit 'use client':
  - Favor server components and Next.js SSR
  - Use only for Web API access in small components
  - Avoid for data fetching or state management

> Follow Next.js docs for Data Fetching, Rendering, and Routing.

## Git Usage
- Use the following prefixes for commit messages followed by a colon and a space:
  - `fix` for bug fixes
  - `feat` for new features
  - `perf` for performance improvements
  - `docs` for documentation changes
  - `style` for formatting changes
  - `refactor` for code refactoring
  - `test` for adding missing tests
  - `chore` for chore tasks
- When determining the commit message prefix, pick the most relevant prefix from the list above
- Use lower case for commit messages
- The commit message should also include a list of the changes made in this commit after the summary line if the changes are not self-explanatory
css
javascript
next.js
radix-ui
react
shadcn/ui
tailwindcss
typescript
loschke/HelpBaerAI_Prompt-Library

Used in 1 repository