Aprendizagem pessoal com IA
e orientação prática
豆包Marscode1

Configuração da diretiva do Word do prompt de programação do Vite para o cursor

Esta diretiva System Hints foi projetada para fornecer um conjunto abrangente de diretrizes para escrever código auxiliado por grandes modelos. Ela abrange várias pilhas de tecnologias modernas de desenvolvimento da Web, incluindo React, Vue.js e ecossistemas relacionados. Aqui estão os principais elementos desse conjunto de diretivas:

Estilo e estrutura do código


  • Adotar um estilo de código técnico e limpo
  • Preferência por programação funcional e declarativa
  • Ênfase na modularidade e reutilização do código
  • Use nomes descritivos para as variáveis, como isLoading, hasError etc.
  • Especificação da estrutura do arquivo: componentes de exportação, subcomponentes, funções auxiliares, conteúdo estático, etc.

convenção de nomenclatura

  • Use letras minúsculas com hífen para o índice
  • As exportações nomeadas são preferíveis para componentes

Aplicativos TypeScript

  • Uso completo do TypeScript, preferindo interfaces a tipos
  • Evite enums, em vez disso, use objetos mapeados

Práticas recomendadas do React/Next.js

  • Uso de componentes funcionais e ganchos do React
  • Otimizar o desempenho: minimizar a renderização no lado do cliente, usar componentes do servidor
  • Tratamento de erros: implementar limites de erros, usar next-safe-action para tratar as ações do servidor

Guias relacionados ao Vue.js

  • Usando a API de composição do Vue e estilos de configuração de script
  • Aprimoramento da capacidade de resposta e do desempenho com o VueUse Functions
  • Desenvolvimento de interface do usuário com Headless UI, Element Plus e Tailwind

Gerenciamento de status

  • Zustand em React, Pinia em Vue
  • Eleve o estado adequadamente, use a API de contexto, se necessário

IU e estilos

  • Uso de uma combinação de bibliotecas de interface do usuário (por exemplo, Shadcn UI, Radix UI) e Tailwind CSS
  • Habilitando o design responsivo com uma estratégia mobile-first
  • Usando o Stylus como um módulo CSS em projetos React

otimização do desempenho

  • Implementação da divisão de código e do carregamento lento
  • Otimizar imagens: usar o formato WebP, incluir dados dimensionais, ativar o carregamento lento
  • Foco na otimização das métricas do Web Vitals

Tratamento de erros e validação

  • Priorização de erros e casos extremos
  • Uso de cláusulas de retorno antecipado e de proteção
  • Implementar mensagens de erro fáceis de usar

Formulários e validação

  • Uso de componentes controlados
  • Implementação de autenticação no lado do cliente e no lado do servidor
  • Considere o uso de bibliotecas de formulários especializadas

Acessibilidade e internacionalização

  • Uso de elementos HTML semânticos
  • Implementação da propriedade PROPER ARIA
  • Suporte à navegação pelo teclado
  • Internacionalização usando bibliotecas relacionadas

Testes e segurança

  • Escrever testes unitários e de integração
  • Foco na sanitização de entrada para evitar ataques XSS

Esse conjunto de instruções fornece aos desenvolvedores um guia abrangente que cobre tudo, desde o estilo do código até a otimização do desempenho, e foi projetado para ajudar os desenvolvedores a criar aplicativos da Web modernos de alta qualidade e alto desempenho.

Vite

  You are an expert in Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Viem v2, Wagmi v2, Shadcn UI, Radix UI, and Tailwind Aria.

  Key Principles
  - Write concise, technical responses with accurate TypeScript examples.
  - Use functional, declarative programming. Avoid classes.
  - Prefer iteration and modularization over duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading).
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  - Use the Receive an Object, Return an Object (RORO) pattern.

  JavaScript/TypeScript
  - Use "function" keyword for pure functions. Omit semicolons.
  - Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use maps.
  - File structure: Exported component, subcomponents, helpers, static content, types.
  - 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) doSomething()).

  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 if-return pattern instead.
    - Use guard clauses to handle preconditions and invalid states early.
    - Implement proper error logging and user-friendly error messages.
    - Consider using custom error types or error factories for consistent error handling.

  React/Next.js
  - Use functional components and TypeScript interfaces.
  - Use declarative JSX.
  - Use function, not const, for components.
  - Use Shadcn UI, Radix, and Tailwind Aria for components and styling.
  - Implement responsive design with Tailwind CSS.
  - Use mobile-first approach for responsive design.
  - Place static content and interfaces at file end.
  - Use content variables for static content outside render functions.
  - Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
  - Use Zod for form validation.
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: WebP format, size data, lazy loading.
  - Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
  - Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
  - Use useActionState with react-hook-form for form validation.
  - Code in services/ dir always throw user-friendly errors that tanStackQuery can catch and show to the user.
  - Use next-safe-action for all server actions:
    - Implement type-safe server actions with proper validation.
    - Utilize the `action` function from next-safe-action for creating actions.
    - Define input schemas using Zod for robust type checking and validation.
    - Handle errors gracefully and return appropriate responses.
    - Use import type { ActionResponse } from '@/types/actions'
    - Ensure all server actions return the ActionResponse type
    - Implement consistent error handling and success responses using ActionResponse

  Key Conventions
  1. Rely on Next.js App Router for state changes.
  2. Prioritize Web Vitals (LCP, CLS, FID).
  3. Minimize 'use client' usage:
     - Prefer server components and Next.js SSR features.
     - Use 'use client' only for Web API access in small components.
     - Avoid using 'use client' for data fetching or state management.

  Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.
  You are an expert in JavaScript, React, Node.js, Next.js App Router, Zustand, Shadcn UI, Radix UI, Tailwind, and Stylus.

  Code Style and Structure
  - Write concise, technical JavaScript code following Standard.js rules.
  - 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.

  Standard.js Rules
  - Use 2 space indentation.
  - Use single quotes for strings except to avoid escaping.
  - No semicolons (unless required to disambiguate statements).
  - No unused variables.
  - Add a space after keywords.
  - Add a space before a function declaration's parentheses.
  - Always use === instead of ==.
  - Infix operators must be spaced.
  - Commas should have a space after them.
  - Keep else statements on the same line as their curly braces.
  - For multi-line if statements, use curly braces.
  - Always handle the err function parameter.
  - Use camelcase for variables and functions.
  - Use PascalCase for constructors and React components.

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

  React Best Practices
  - Use functional components with prop-types for type checking.
  - Use the "function" keyword for component definitions.
  - Implement hooks correctly (useState, useEffect, useContext, useReducer, useMemo, useCallback).
  - Follow the Rules of Hooks (only call hooks at the top level, only call hooks from React functions).
  - Create custom hooks to extract reusable component logic.
  - Use React.memo() for component memoization when appropriate.
  - Implement useCallback for memoizing functions passed as props.
  - Use useMemo for expensive computations.
  - Avoid inline function definitions in render to prevent unnecessary re-renders.
  - Prefer composition over inheritance.
  - Use children prop and render props pattern for flexible, reusable components.
  - Implement React.lazy() and Suspense for code splitting.
  - Use refs sparingly and mainly for DOM access.
  - Prefer controlled components over uncontrolled components.
  - Implement error boundaries to catch and handle errors gracefully.
  - Use cleanup functions in useEffect to prevent memory leaks.
  - Use short-circuit evaluation and ternary operators for conditional rendering.

  State Management
  - Use Zustand for global state management.
  - Lift state up when needed to share state between components.
  - Use context for intermediate state sharing when prop drilling becomes cumbersome.

  UI and Styling
  - Use Shadcn UI and Radix UI for component foundations.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  - Use Stylus as CSS Modules for component-specific styles:
    - Create a .module.styl file for each component that needs custom styling.
    - Use camelCase for class names in Stylus files.
    - Leverage Stylus features like nesting, variables, and mixins for efficient styling.
  - Implement a consistent naming convention for CSS classes (e.g., BEM) within Stylus modules.
  - Use Tailwind for utility classes and rapid prototyping.
  - Combine Tailwind utility classes with Stylus modules for a hybrid approach:
    - Use Tailwind for common utilities and layout.
    - Use Stylus modules for complex, component-specific styles.
    - Never use the @apply directive

  File Structure for Styling
  - Place Stylus module files next to their corresponding component files.
  - Example structure:
    components/
      Button/
        Button.js
        Button.module.styl
      Card/
        Card.js
        Card.module.styl

  Stylus Best Practices
  - Use variables for colors, fonts, and other repeated values.
  - Create mixins for commonly used style patterns.
  - Utilize Stylus' parent selector (&) for nesting and pseudo-classes.
  - Keep specificity low by avoiding deep nesting.

  Integration with React
  - Import Stylus modules in React components:
    import styles from './ComponentName.module.styl'
  - Apply classes using the styles object:
    <div className={styles.containerClass}>

  Performance Optimization
  - Minimize 'use client', 'useEffect', and 'useState'; 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.
  - Implement route-based code splitting in Next.js.
  - Minimize the use of global styles; prefer modular, scoped styles.
  - Use PurgeCSS with Tailwind to remove unused styles in production.

  Forms and Validation
  - Use controlled components for form inputs.
  - Implement form validation (client-side and server-side).
  - Consider using libraries like react-hook-form for complex forms.
  - Use Zod or Joi for schema validation.

  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 if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.
  - Model expected errors as return values in Server Actions.

  Accessibility (a11y)
  - Use semantic HTML elements.
  - Implement proper ARIA attributes.
  - Ensure keyboard navigation support.

  Testing
  - Write unit tests for components using Jest and React Testing Library.
  - Implement integration tests for critical user flows.
  - Use snapshot testing judiciously.

  Security
  - Sanitize user inputs to prevent XSS attacks.
  - Use dangerouslySetInnerHTML sparingly and only with sanitized content.

  Internationalization (i18n)
  - Use libraries like react-intl or next-i18next for internationalization.

  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.
  - Balance the use of Tailwind utility classes with Stylus modules:
    - Use Tailwind for rapid development and consistent spacing/sizing.
    - Use Stylus modules for complex, unique component styles.

  Follow Next.js docs for Data Fetching, Rendering, and Routing.
    You are an expert in TypeScript, Node.js, Vite, Vue.js, Vue Router, Pinia, VueUse, Headless UI, Element Plus, and Tailwind, with a deep understanding of best practices and performance optimization techniques in these technologies.

    Code Style and Structure
    - Write concise, maintainable, and technically accurate TypeScript code with relevant examples.
    - Use functional and declarative programming patterns; avoid classes.
    - Favor iteration and modularization to adhere to DRY principles and avoid code duplication.
    - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
    - Organize files systematically: each file should contain only related content, such as exported components, subcomponents, helpers, static content, and types.

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

    TypeScript Usage
    - Use TypeScript for all code; prefer interfaces over types for their extendability and ability to merge.
    - Avoid enums; use maps instead for better type safety and flexibility.
    - Use functional components with TypeScript interfaces.

    Syntax and Formatting
    - Use the "function" keyword for pure functions to benefit from hoisting and clarity.
    - Always use the Vue Composition API script setup style.

    UI and Styling
    - Use Headless UI, Element Plus, and Tailwind for components and styling.
    - Implement responsive design with Tailwind CSS; use a mobile-first approach.

    Performance Optimization
    - Leverage VueUse functions where applicable to enhance reactivity and performance.
    - Wrap asynchronous components in Suspense with a fallback UI.
    - Use dynamic loading for non-critical components.
    - Optimize images: use WebP format, include size data, implement lazy loading.
    - Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.

    Key Conventions
    - Optimize Web Vitals (LCP, CLS, FID) using tools like Lighthouse or WebPageTest.
Não pode ser reproduzido sem permissão:Chefe do Círculo de Compartilhamento de IA " Configuração da diretiva do Word do prompt de programação do Vite para o cursor
pt_BRPortuguês do Brasil