frontend-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFrontend Development
前端开发
Next.js (latest) App Router with TypeScript. Server-first architecture.
Related Skills:
- USE FIRST for Kavak-specific patterns, GitLab CI, Docker templateskavak-documentation - USE THIS for performance (bundle size, waterfalls, caching, re-renders, memoization)vercel-react-best-practices- Check
for project-specific conventions.claude/CLAUDE.md- Check
for project-specific conventions.cursor/rules/*MCP:
- Use
tool to query Kavak internal documentation before implementingkavak-platform/plati_query- Use
MCP server if available for debugging, route inspection, and build analysisnext-devtools
使用TypeScript的最新版Next.js App Router,采用服务器优先架构。
相关技能:
- 优先使用,适用于Kavak特定模式、GitLab CI、Docker模板kavak-documentation - 使用此技能优化性能(包体积、请求瀑布、缓存、重渲染、记忆化)vercel-react-best-practices- 查看
了解项目特定规范.claude/CLAUDE.md- 查看
了解项目特定规范.cursor/rules/*MCP:
- 实现功能前,使用
工具查询Kavak内部文档kavak-platform/plati_query- 若有可用的
MCP服务器,可用于调试、路由检查和构建分析next-devtools
Quick Start
快速开始
| Task | Pattern |
|---|---|
| New page | Server Component by default |
| Data fetching | Server Component async fetch |
| Mutations | Server Actions + Zod + revalidatePath |
| Styling | MUI |
| State | Server = fetch, Client = useState only when needed |
| 任务 | 实现模式 |
|---|---|
| 新建页面 | 默认使用Server Component |
| 数据获取 | Server Component异步fetch |
| 数据变更 | Server Actions + Zod + revalidatePath |
| 样式处理 | MUI |
| 状态管理 | 服务器端=fetch,客户端=仅在必要时使用useState |
Core Principles
核心原则
- Server by Default: Components are Server Components unless they need /
useState/eventsuseEffect - Server Actions for Mutations: Replace API routes for internal app logic
- Opt-in Caching: Use directive for explicit caching
'use cache' - Minimal Client JS: Keep components small and leaf-level
'use client' - Type Everything: Strict TypeScript, Zod for runtime validation
Performance: For bundle optimization, waterfalls, memoization, seevercel-react-best-practices
- 默认服务器端渲染:组件默认是Server Components,除非需要/
useState或事件处理useEffect - 用Server Actions处理数据变更:替代API路由实现内部应用逻辑
- 显式缓存:使用指令启用缓存
'use cache' - 最小化客户端JS:保持组件体积小巧且为叶子节点
'use client' - 全类型化:严格的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
新功能开发
- Create (Server Component)
app/{route}/page.tsx - Add for Suspense boundary
loading.tsx - Create Server Actions in
actions.ts - Add Client Components only where needed
- 创建(Server Component)
app/{route}/page.tsx - 添加作为Suspense边界
loading.tsx - 在中创建Server Actions
actions.ts - 仅在必要时添加客户端组件
Performance Issue
性能问题排查
→ Run skill for optimization rules
vercel-react-best-practices→ 运行技能获取优化规则
vercel-react-best-practicesStyling Component
组件样式处理
- Use MUI prop with
sxSxProps<Theme> - Inline styles if <100 lines, separate if >100
.styles.ts - Grid:
size={{ xs: 12, md: 6 }}
- 使用带的MUI
SxProps<Theme>属性sx - 代码少于100行时内联样式,超过100行时单独创建
.styles.ts - Grid组件:
size={{ xs: 12, md: 6 }}
References
参考文档
| Reference | When to Use |
|---|---|
| App Router, RSC, Server Actions, caching |
| React.FC, hooks order, dialogs, forms |
| MUI sx prop, Grid, theming |
| Types, generics, Zod validation |
| features/ vs components/, organization |
Performance/Optimization → skill
vercel-react-best-practices| 参考文档 | 使用场景 |
|---|---|
| App Router、RSC、Server Actions、缓存 |
| React.FC、钩子顺序、对话框、表单 |
| MUI sx属性、Grid、主题配置 |
| 类型、泛型、Zod校验 |
| features/ vs components/、项目组织 |
性能/优化 → 参考技能
vercel-react-best-practicesTechnology Stack
技术栈
| Layer | Technology |
|---|---|
| Framework | Next.js (App Router, latest) |
| Type Safety | TypeScript (strict) + Zod |
| Data Fetching | Server Components (async) |
| Mutations | Server Actions + revalidatePath |
| Client State | useState (minimal) |
| Styling | MUI (latest) |
| Forms | Server 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