Communitygithub.com

ComeOnOliver/skillshub

用于处理 Next.js App Router 任务时使用——在 /app/ 中创建页面、设置动态路由([id]/page.tsx)、实现嵌套布局/模板(layout.tsx)、优化服务端/客户端组件,以及构建基于角色的 ERP 页面(管理员/教师/学生仪表板)。自动用于所有 /app/ 目录操作、动态路由和 App Router 特有功能。

skillshub 是什么?

该技能为 Next.js App Router 开发提供专业指导,涵盖页面创建、动态路由、嵌套布局、服务端/客户端组件优化以及基于角色的 ERP 仪表板等核心功能。它推荐默认使用服务端组件进行数据获取,并利用 `Suspense` 和错误边界来增强用户体验。技能文档内包含代码模板、工作流决策树和质量检查清单,可帮助开发者高效构建生产级别的应用。该技能主要面向 Next.js App Router 项目,可自动应用于所有 `/app/` 目录操作、动态路由配置及 App Router 特有功能。它通过清晰的模板和最佳实践,引导开发者从需求分析到实现路径,确保代码符合 TypeScript 严格模式、SEO 优化和响应式设计等标准。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/awais68/frontend-nextjs-app-router

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Next.js App Router 专家指南

概述

提供 Next.js App Router 开发的专家指导,包括页面创建、动态路由、嵌套布局、服务端/客户端组件优化以及基于角色的 ERP 仪表板。

核心功能

1. 页面创建(/app/.../page.tsx)

规则:

  • 默认使用服务端组件(不使用 'use client' 指令)
  • 使用 fetch() 或 ORM 查询直接进行异步数据获取
  • 初始数据加载不使用 useEffect
  • 使用 Suspense 边界处理加载状态
  • 通过 generateMetadata() 设置 SEO 元数据

模板:

// app/dashboard/page.tsx
import { Suspense } from 'react';
import { TaskList } from '@/components/TaskList';
import { TaskListSkeleton } from '@/components/TaskListSkeleton';

export const metadata = {
  title: '仪表板',
  description: '您的任务管理仪表板',
};

export default async function DashboardPage() {
  const tasks = await fetchTasks();

  return (
    <main className="p-4">
      <h1>仪表板</h1>
      <Suspense fallback={<TaskListSkeleton />}>
        <TaskList initialTasks={tasks} />
      </Suspense>
    </main>
  );
}

2. 动态路由([slug]/page.tsx)

适用场景:

  • 学生档案:app/students/[studentId]/page.tsx
  • 任务详情:app/tasks/[taskId]/page.tsx
  • 课程页面:app/courses/[courseId]/page.tsx

规则:

  • 从 params 属性中提取参数(只读)
  • 使用 generateMetadata() 进行 SEO
  • 通过 not-found.tsx 处理 404

模板:

// app/students/[studentId]/page.tsx
import { notFound } from 'next/navigation';

type Params = Promise<{ studentId: string }>;

export async function generateMetadata({ params }: { params: Params }) {
  const { studentId } = await params;
  const student = await getStudent(studentId);

  if (!student) return { title: '学生未找到' };

  return {
    title: `${student.name} - 学生档案`,
  };
}

export default async function StudentProfile({ params }: { params: Params }) {
  const { studentId } = await params;
  const student = await getStudent(studentId);

  if (!student) notFound();

  return <StudentProfileView student={student} />;
}

3. 并行路由(@folder)

适用场景:

  • 仪表板变体:app/dashboard@(admin|teacher)/page.tsx
  • 拆分布局:app/settings@(user|organization)/layout.tsx

模板:

// app/dashboard/@admin/page.tsx - 管理员仪表板
export default function AdminDashboard() {
  return <AdminPanel />;
}

// app/dashboard/@teacher/page.tsx - 教师仪表板
export default function TeacherDashboard() {
  return <TeacherPanel />;
}

4. 布局与模板

根布局(app/layout.tsx):

import { Providers } from '@/components/Providers';
import './globals.css';

export const metadata = {
  title: 'Todo Evolution',
  description: '面向教育的任务管理',
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

嵌套布局(app/dashboard/layout.tsx):

import { DashboardNav } from '@/components/DashboardNav';

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="flex min-h-screen">
      <DashboardNav />
      <main className="flex-1 p-6">{children}</main>
    </div>
  );
}

模板(app/tasks/template.tsx):

// 导航时重新执行,保留表单状态
export default function TasksTemplate({ children }: { children: React.ReactNode }) {
  return (
    <div className="bg-gray-50 min-h-screen">
      <header className="bg-white shadow">
        <h1>任务</h1>
      </header>
      {children}
    </div>
  );
}

5. 服务端组件与客户端组件

服务端组件适用于:

  • 数据获取
  • 直接数据库查询
  • 静态内容
  • 仅限服务端的操作

客户端组件('use client')适用于:

  • 浏览器 API(window、localStorage)
  • 事件处理(onClick、onSubmit)
  • React hooks(useState、useEffect)
  • 状态管理(Zustand、Redux)
  • 交互功能
// 服务端组件(默认)
export default async function TaskList() {
  const tasks = await fetchTasks(); // 直接数据库查询
  return <div>{tasks.map(/* ... */)}</div>;
}

// 客户端组件
'use client';
import { useTaskStore } from '@/store/tasks';

export function TaskFilter() {
  const { filter, setFilter } = useTaskStore();
  return <button onClick={() => setFilter('all')}>全部任务</button>;
}

6. 基于角色的 ERP 页面

角色守卫:

// app/admin/page.tsx
import { requireRole } from '@/lib/auth';
import { redirect } from 'next/navigation';

export default async function AdminPage() {
  const session = await getSession();

  if (session?.role !== 'admin') {
    redirect('/unauthorized');
  }

  return <AdminDashboard />;
}

KPI 仪表板(Recharts):

'use client';
import { BarChart, Bar, XAxis, YAxis, Tooltip } from 'recharts';

export function TaskKPIChart({ data }: { data: TaskStats[] }) {
  return (
    <BarChart width={600} height={300} data={data}>
      <XAxis dataKey="date" />
      <YAxis />
      <Tooltip />
      <Bar dataKey="completed" fill="#22c55e" />
    </BarChart>
  );
}

7. 错误与加载状态

错误边界(error.tsx):

'use client';
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div>
      <h2>出现了一些问题!</h2>
      <button onClick={reset}>重试</button>
    </div>
  );
}

加载状态(loading.tsx):

export default function Loading() {
  return <div className="animate-pulse">加载中...</div>;
}

// 或者使用 Suspense:
export default async function Page() {
  return (
    <Suspense fallback={<Loading />}>
      <Content />
    </Suspense>
  );
}

8. shadcn/ui 集成

安装:

npx shadcn@latest add button card input dialog

在服务端组件中使用:

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';

export default async function TaskPage() {
  const tasks = await getTasks();

  return (
    <Card>
      <CardHeader>任务</CardHeader>
      <CardContent>
        {tasks.map(task => (
          <div key={task.id}>{task.title}</div>
        ))}
      </CardContent>
    </Card>
  );
}

工作流决策树

用户请求 → 分析 → 实现路径

  1. “创建一个仪表板/管理员页面” → 服务端组件,使用 page.tsx → 异步数据获取 → 如需导航则添加 layout.tsx

  2. “动态学生档案” → 创建 [studentId]/page.tsx → 提取参数 → 添加 generateMetadata() → 如需则创建 not-found.tsx

  3. “添加共享布局” → 在目标文件夹中创建 layout.tsx → 如需则包裹 providers → 保持 children 渲染

  4. “添加表单” → 'use client' 组件 → 使用 useState 管理表单数据 → 使用 Server Action 或 API 路由进行提交

  5. “KPI 图表/分析” → 使用 'use client' 引入 Recharts → 服务端组件作为父组件负责数据获取 → 将数据作为 props 传递

质量检查清单

在标记任务完成前,请确保:

  • 启用 TypeScript 严格模式
  • 默认使用服务端组件
  • 仅在必要时使用 'use client'
  • 使用 generateMetadata() 进行 SEO
  • 为异步数据设置 Suspense 边界
  • 在需要的地方设置错误边界(error.tsx)
  • 无 hydration 不匹配
  • 性能优化(无阻塞渲染)
  • 移动优先的响应式设计
  • 可访问性(ARIA 标签、键盘导航)

常见模式

模式 1:服务端组件与客户端组件混合

// 服务端组件
export default async function Page() {
  const tasks = await fetchTasks();
  return <TaskList tasks={tasks} />; // 客户端组件用于交互
}

'use client';
function TaskList({ tasks }: { tasks: Task[] }) {
  const [filter, setFilter] = useState('all');
  const filtered = tasks.filter(/* ... */);
  return <div>{filtered.map(/* ... */)}</div>;
}

模式 2:用于组织的路由组

app/
  (marketing)/     # 组:无 URL 段
    about/page.tsx
    contact/page.tsx
  (dashboard)/      # 组:无 URL 段
    layout.tsx
    page.tsx

模式 3:API 路由(路由处理器)

// app/api/tasks/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const tasks = await db.query.tasks.findMany();
  return NextResponse.json(tasks);
}

export async function POST(request: Request) {
  const body = await request.json();
  const task = await createTask(body);
  return NextResponse.json(task, { status: 201 });
}

触发示例

  • “创建一个仪表板页面” → 生成 app/dashboard/page.tsx,使用服务端组件
  • “动态学生档案路由” → app/students/[studentId]/page.tsx,带参数和元数据
  • “添加共享布局” → app/dashboard/layout.tsx,包含 children
  • “带图表的管理员面板” → 服务端组件 + 客户端图表组件
  • “创建登录页面” → 'use client' 表单组件 + API 路由
  • “自定义 404 页面” → app/not-found.tsx
  • “处理错误” → app/dashboard/error.tsx

参考资料

有关更高级的模式,请参阅 references/app-router-patterns.md;有关路由处理器的示例,请参阅 references/api-routes.md。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能