AgentSkillsCN

frontend-dev-guidelines

React/TypeScript 应用程序的前端开发规范。涵盖现代模式,包括 Suspense、懒加载、useSWR、以 features 目录组织文件、shadcn/ui 组件、Tailwind CSS 样式、Next.js App Router、性能优化,以及 TypeScript 最佳实践。适用于创建组件、页面、功能、获取数据、进行样式设计、配置路由,或在前端代码中开展工作时使用。

SKILL.md
--- frontmatter
name: frontend-dev-guidelines
description: Frontend development guidelines for React/TypeScript applications. Modern patterns including Suspense, lazy loading, useSWR, file organization with features directory, shadcn/ui components, Tailwind CSS styling, Next.js App Router, performance optimization, and TypeScript best practices. Use when creating components, pages, features, fetching data, styling, routing, or working with frontend code.

Frontend Dev Guidelines (Senior Level)

This skill is at senior frontend developer knowledge level. Memorize patterns, recognize edge cases, reject anti-patterns.


1. Senior Developer Mindset

Think performance-first:

  • Ask "is this causing unnecessary renders?" for every component
  • Detect network waterfalls, use parallel fetch
  • Monitor bundle size, lazy load heavy components

Internalize patterns:

  • React.FC<Props> + TypeScript always
  • useSWR with suspense: true is standard
  • SuspenseLoader NEVER early return with spinner

Reject anti-patterns:

  • Convert barrel file imports to direct imports
  • Replace sequential await with Promise.all()
  • Replace hardcoded colors with globals.css variables

2. Non-Negotiables (CRITICAL)

Component Patterns

typescript
// ✅ STANDARD PATTERN
import React from 'react';
import useSWR from 'swr';
import { SuspenseLoader } from '@/shared/components/SuspenseLoader';

const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

interface MyComponentProps {
    id: string;
    className?: string;
}

export const MyComponent: React.FC<MyComponentProps> = ({ id, className }) => {
    const { data } = useSWR(`key-${id}`, () => api.get(id), { suspense: true });
    return <div className={cn("base-class", className)}>{data?.title}</div>;
};

// Usage - with Suspense boundary
<SuspenseLoader>
    <MyComponent id="123" />
</SuspenseLoader>

Performance Rules (Top 15)

PriorityRuleDescription
CRITICALPromise.all()Parallelize independent async operations
CRITICALDirect importsAvoid barrel files, import directly
CRITICALnext/dynamicDynamic import heavy components
CRITICALSuspense boundariesStream content, prevent waterfalls
HIGHDefer awaitMove await to the branch where it's used
HIGHMinimize RSC serializationSend less data to client
HIGHReact.cache()Per-request deduplication
MEDIUMSWR deduplicationAuto request deduplication
MEDIUMFunctional setStatesetCount(c => c + 1) stable callback
MEDIUMLazy state inituseState(() => expensiveCalc())
MEDIUMstartTransitionFor non-urgent updates
MEDIUMcontent-visibilityCSS optimize for long lists
LOWIndex mapsUse Map for repeated lookups
LOWtoSorted()For immutable sort
LOWSet/Map lookupsO(1) lookup instead of array

Accessibility Rules (Top 10)

RuleDescription
aria-label on icon buttonsALWAYS add aria-label to icon-only buttons
button vs a/LinkAction = button, Navigation = a/Link
alt on imagesAdd alt to every img (decorative: alt="")
Keyboard handlersAdd keyboard support to interactive elements
Heading hierarchyMaintain h1 → h2 → h3 order
autocomplete on inputsAdd autocomplete to form inputs
Inline errorsShow errors next to field
Submit button enabledDon't disable submit, show loading spinner
Virtualize long listsVirtualize lists with 50+ items
prefers-reduced-motionCheck motion preference in animations

3. Browser Compatibility (SAFARI CRITICAL)

Check Safari on every code change! Safari is the most problematic browser.

IssueSafari FixReference
new Date('2024-01-15 10:30:00')ISO 8601: '2024-01-15T10:30:00'browser-compatibility.md
height: 100vhheight: 100dvh or -webkit-fill-availablebrowser-compatibility.md
backdrop-filterAdd -webkit-backdrop-filter prefixbrowser-compatibility.md
Video autoplayplaysInline + muted attributesbrowser-compatibility.md
Input zoom (iOS)font-size: 16px minimumbrowser-compatibility.md
Touch events{ passive: true } listenerbrowser-compatibility.md
Clipboard APIFallback textarea methodbrowser-compatibility.md

Test Checklist (Every PR):

  • Chrome (latest)
  • Safari (macOS)
  • Safari (iOS) - Real device or simulator
  • Firefox (latest)

4. Anti-Patterns (NEVER DO)

Anti-PatternCorrect PatternReference
if (isLoading) return <Spinner />Wrap with <SuspenseLoader>core-patterns.md
Sequential awaitUse Promise.all()performance-guide.md
Barrel file importUse direct importperformance-guide.md
Hardcoded color bg-[#fe4601]CSS variable bg-orange-1styling-routing.md
<div onClick><button onClick>accessibility-guide.md
Icon button without labelAdd aria-labelaccessibility-guide.md
Server data in useStateUse useSWRcore-patterns.md
next/router importUse next/navigationstyling-routing.md
dangerouslySetInnerHTMLDOMPurify sanitizationsecurity-error-handling.md
any typeunknown + type guardadvanced-typescript.md
Type assertion as UserRuntime validation (Zod)advanced-typescript.md

5. Decision Trees

useState vs Zustand vs SWR

code
What's the data source?
├─ Server/API → SWR (suspense: true)
├─ Form input → useState (local)
├─ UI state (modal, sidebar) → useState (local)
└─ Shared across components?
   ├─ Server data → SWR (auto-shares)
   └─ Client state → Zustand (ONLY)

Server vs Client Component

code
What does the component do?
├─ Static content → Server Component
├─ Data fetch (no interaction) → Server Component
├─ Needs useState/useEffect → Client Component
├─ Has onClick/onChange handler → Client Component
├─ Uses Browser API → Client Component
└─ Third-party client library → Client Component

useMemo vs React.memo vs useCallback

code
What are you optimizing?
├─ Expensive calculation → useMemo
├─ Object/array reference stability → useMemo
├─ Function reference stability → useCallback
├─ Child component re-render → React.memo (on child)
└─ Event handler in dependency → useCallback

Lazy Loading Decision

code
Is the component heavy?
├─ DataGrid/Table → lazy load
├─ Chart/Graph → lazy load
├─ Rich text editor → lazy load
├─ Video player → lazy load
├─ Small utility component → don't lazy load
└─ Above-the-fold critical → don't lazy load

6. Quick Reference

For detailed info: styling-routing.md

TopicSource
Import aliases (@/, @/shared, @/features)styling-routing.md
Feature directory structurestyling-routing.md
Route groups ((dashboard), (main), etc.)styling-routing.md
Color palettes (globals.css)styling-routing.md

7. Resources (Detailed Info)

TopicResource
Component, data fetching, React 19 hooks, statecore-patterns.md
All performance rules (45 rules)performance-guide.md
Accessibility patterns (WCAG 2.1)accessibility-guide.md
Tailwind, routing, file organizationstyling-routing.md
Testing patterns, complete examplestesting-examples.md
Safari/Chrome/Firefox compatibility, Senior FE skillsbrowser-compatibility.md
XSS/CSRF prevention, error boundaries, resiliencesecurity-error-handling.md
Generics, type guards, utility types, inferenceadvanced-typescript.md

Quick Template

typescript
import React from 'react';
import useSWR from 'swr';
import { Card, CardHeader, CardTitle, CardContent } from '@/shared/components/ui/card';
import { cn } from '@/shared/utils/cn';
import { featureApi } from '../api/featureApi';

interface FeatureCardProps {
    id: string;
    className?: string;
}

export const FeatureCard: React.FC<FeatureCardProps> = ({ id, className }) => {
    const { data } = useSWR(`feature-${id}`, () => featureApi.get(id), { suspense: true });

    return (
        <Card className={cn("w-full", className)}>
            <CardHeader>
                <CardTitle>{data?.title}</CardTitle>
            </CardHeader>
            <CardContent>
                <p className="text-muted-foreground">{data?.description}</p>
            </CardContent>
        </Card>
    );
};

Related Skills

  • react-best-practices: Full 45 performance rules (Vercel Engineering)
  • web-design-guidelines: Full UI/UX/a11y rules (Vercel Labs)
  • error-tracking: Sentry integration