frontend-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Frontend Development

前端开发

Next.js (latest) App Router with TypeScript. Server-first architecture.
Related Skills:
  • kavak-documentation
    - USE FIRST for Kavak-specific patterns, GitLab CI, Docker templates
  • vercel-react-best-practices
    - USE THIS for performance (bundle size, waterfalls, caching, re-renders, memoization)
  • Check
    .claude/CLAUDE.md
    for project-specific conventions
  • Check
    .cursor/rules/*
    for project-specific conventions
MCP:
  • Use
    kavak-platform/plati_query
    tool to query Kavak internal documentation before implementing
  • Use
    next-devtools
    MCP server if available for debugging, route inspection, and build analysis
使用TypeScript的最新版Next.js App Router,采用服务器优先架构。
相关技能:
  • kavak-documentation
    - 优先使用,适用于Kavak特定模式、GitLab CI、Docker模板
  • vercel-react-best-practices
    - 使用此技能优化性能(包体积、请求瀑布、缓存、重渲染、记忆化)
  • 查看
    .claude/CLAUDE.md
    了解项目特定规范
  • 查看
    .cursor/rules/*
    了解项目特定规范
MCP:
  • 实现功能前,使用
    kavak-platform/plati_query
    工具查询Kavak内部文档
  • 若有可用的
    next-devtools
    MCP服务器,可用于调试、路由检查和构建分析

Quick Start

快速开始

TaskPattern
New pageServer Component by default
Data fetchingServer Component async fetch
MutationsServer Actions + Zod + revalidatePath
StylingMUI
sx
prop, inline if <100 lines
StateServer = fetch, Client = useState only when needed
任务实现模式
新建页面默认使用Server Component
数据获取Server Component异步fetch
数据变更Server Actions + Zod + revalidatePath
样式处理MUI
sx
属性,代码少于100行时内联
状态管理服务器端=fetch,客户端=仅在必要时使用useState

Core Principles

核心原则

  1. Server by Default: Components are Server Components unless they need
    useState
    /
    useEffect
    /events
  2. Server Actions for Mutations: Replace API routes for internal app logic
  3. Opt-in Caching: Use
    'use cache'
    directive for explicit caching
  4. Minimal Client JS: Keep
    'use client'
    components small and leaf-level
  5. Type Everything: Strict TypeScript, Zod for runtime validation
Performance: For bundle optimization, waterfalls, memoization, see
vercel-react-best-practices
  1. 默认服务器端渲染:组件默认是Server Components,除非需要
    useState
    /
    useEffect
    或事件处理
  2. 用Server Actions处理数据变更:替代API路由实现内部应用逻辑
  3. 显式缓存:使用
    'use cache'
    指令启用缓存
  4. 最小化客户端JS:保持
    'use client'
    组件体积小巧且为叶子节点
  5. 全类型化:严格的TypeScript,用Zod做运行时校验
性能优化:关于包体积优化、请求瀑布、记忆化等内容,查看
vercel-react-best-practices
技能

Server vs Client Decision

服务器端vs客户端组件决策

Need useState/useEffect/onClick? → 'use client'
Need browser APIs (localStorage)? → 'use client'
Just rendering data? → Server Component (default)
Rule: Keep Client Components small. Most of tree stays server-rendered.
需要useState/useEffect/onClick? → 'use client'
需要浏览器API(如localStorage)? → 'use client'
仅渲染数据? → Server Component(默认)
规则:保持客户端组件体积小巧。组件树的大部分应保持服务器端渲染。

Data Fetching Pattern

数据获取模式

typescript
// app/users/page.tsx - Server Component (default)
export default async function UsersPage() {
    const users = await db.user.findMany();  // Runs on server
    return <UserList users={users} />;
}
No TanStack Query needed - Server Components handle data fetching natively.
typescript
// app/users/page.tsx - Server Component (default)
export default async function UsersPage() {
    const users = await db.user.findMany();  // Runs on server
    return <UserList users={users} />;
}
无需使用TanStack Query - Server Components原生支持数据获取。

Server Actions Pattern

Server Actions实现模式

typescript
// app/actions.ts
'use server';

import { z } from 'zod';
import { revalidatePath } from 'next/cache';

const schema = z.object({ title: z.string().min(1) });

export async function createPost(formData: FormData) {
  const parsed = schema.safeParse({ title: formData.get('title') });
  if (!parsed.success) return { error: parsed.error.flatten() };

  await db.post.create({ data: parsed.data });
  revalidatePath('/posts');
  return { success: true };
}
When to use Server Actions vs API Routes:
  • Server Actions → Internal mutations, form submissions
  • Route Handlers → Public APIs, webhooks, large uploads, streaming
typescript
// app/actions.ts
'use server';

import { z } from 'zod';
import { revalidatePath } from 'next/cache';

const schema = z.object({ title: z.string().min(1) });

export async function createPost(formData: FormData) {
  const parsed = schema.safeParse({ title: formData.get('title') });
  if (!parsed.success) return { error: parsed.error.flatten() };

  await db.post.create({ data: parsed.data });
  revalidatePath('/posts');
  return { success: true };
}
Server Actions与API路由的使用场景对比:
  • Server Actions → 内部数据变更、表单提交
  • Route Handlers → 公开API、Webhook、大文件上传、流处理

Critical Rules

关键规则

Never

禁止操作

typescript
// ❌ Large 'use client' at top of tree
'use client';  // Marks entire subtree as client

// ❌ Expose secrets to client
const apiKey = process.env.SECRET_KEY;  // In client component

// ❌ Old MUI Grid syntax
<Grid xs={12} md={6}>
typescript
// ❌ 在组件树顶层标记大体积'use client'
'use client';  // 标记整个子树为客户端组件

// ❌ 在客户端组件中暴露密钥
const apiKey = process.env.SECRET_KEY;  // 在客户端组件中

// ❌ 旧版MUI Grid语法
<Grid xs={12} md={6}>

Always

推荐操作

typescript
// ✅ Small leaf-level client components
// ✅ Validate Server Action inputs with Zod
// ✅ MUI Grid size prop
<Grid size={{ xs: 12, md: 6 }}>
typescript
// ✅ 小巧的叶子节点客户端组件
// ✅ 用Zod校验Server Action的输入
// ✅ MUI Grid尺寸属性
<Grid size={{ xs: 12, md: 6 }}>

File Conventions

文件规范

app/
├── layout.tsx          # Root layout (Server)
├── page.tsx            # Home page
├── loading.tsx         # Loading UI (Suspense fallback)
├── error.tsx           # Error boundary ('use client')
├── not-found.tsx       # 404 page
├── users/
│   ├── page.tsx        # /users
│   ├── [id]/
│   │   └── page.tsx    # /users/:id
│   └── actions.ts      # Server Actions
└── api/
    └── webhook/
        └── route.ts    # Route Handler (public API)
app/
├── layout.tsx          # 根布局(服务器端)
├── page.tsx            # 首页
├── loading.tsx         # 加载UI(Suspense fallback)
├── error.tsx           # 错误边界('use client')
├── not-found.tsx       # 404页面
├── users/
│   ├── page.tsx        # /users
│   ├── [id]/
│   │   └── page.tsx    # /users/:id
│   └── actions.ts      # Server Actions
└── api/
    └── webhook/
        └── route.ts    # Route Handler(公开API)

Common Workflows

常见工作流

New Feature

新功能开发

  1. Create
    app/{route}/page.tsx
    (Server Component)
  2. Add
    loading.tsx
    for Suspense boundary
  3. Create Server Actions in
    actions.ts
  4. Add Client Components only where needed
  1. 创建
    app/{route}/page.tsx
    (Server Component)
  2. 添加
    loading.tsx
    作为Suspense边界
  3. actions.ts
    中创建Server Actions
  4. 仅在必要时添加客户端组件

Performance Issue

性能问题排查

Run
vercel-react-best-practices
skill
for optimization rules
运行
vercel-react-best-practices
技能
获取优化规则

Styling Component

组件样式处理

  1. Use MUI
    sx
    prop with
    SxProps<Theme>
  2. Inline styles if <100 lines, separate
    .styles.ts
    if >100
  3. Grid:
    size={{ xs: 12, md: 6 }}
  1. 使用带
    SxProps<Theme>
    的MUI
    sx
    属性
  2. 代码少于100行时内联样式,超过100行时单独创建
    .styles.ts
  3. Grid组件:
    size={{ xs: 12, md: 6 }}

References

参考文档

ReferenceWhen to Use
references/nextjs.md
App Router, RSC, Server Actions, caching
references/component-patterns.md
React.FC, hooks order, dialogs, forms
references/styling.md
MUI sx prop, Grid, theming
references/typescript.md
Types, generics, Zod validation
references/project-structure.md
features/ vs components/, organization
Performance/Optimization
vercel-react-best-practices
skill
参考文档使用场景
references/nextjs.md
App Router、RSC、Server Actions、缓存
references/component-patterns.md
React.FC、钩子顺序、对话框、表单
references/styling.md
MUI sx属性、Grid、主题配置
references/typescript.md
类型、泛型、Zod校验
references/project-structure.md
features/ vs components/、项目组织
性能/优化 → 参考
vercel-react-best-practices
技能

Technology Stack

技术栈

LayerTechnology
FrameworkNext.js (App Router, latest)
Type SafetyTypeScript (strict) + Zod
Data FetchingServer Components (async)
MutationsServer Actions + revalidatePath
Client StateuseState (minimal)
StylingMUI (latest)
FormsServer Actions + useActionState
Note: TanStack Query only if you need real-time polling or complex optimistic updates. See
references/data-fetching.md
.
层级技术选型
框架Next.js (App Router, 最新版)
类型安全TypeScript (严格模式) + Zod
数据获取Server Components (异步)
数据变更Server Actions + revalidatePath
客户端状态useState (最小化使用)
样式处理MUI (最新版)
表单处理Server Actions + useActionState
注意:仅当需要实时轮询或复杂乐观更新时才使用TanStack Query。详见
references/data-fetching.md