Communitygithub.com

ComeOnOliver/skillshub

Next.js 15 應用程式的前端開發指南(React 19、TypeScript、Shadcn/ui、Tailwind CSS),涵蓋 Server/Client Components、App Router、檔案組織與效能最佳化。

skillshub 是什麼?

此技能為開發者提供一套基於 Next.js 15 與 React 19 的完整前端開發指南,重點強調 Server Components 與 Client Components 的正確使用時機、App Router 的檔案式路由組織,以及 Shadcn/ui 與 Tailwind CSS 的樣式實務。透過詳細的檢查清單、範例程式碼與最佳實踐說明,協助團隊在建置新元件、頁面或功能時快速遵循一致的模式,包含資料擷取(Server Components / Server Actions)、錯誤與載入狀態處理、型別安全(TypeScript Strict)及效能最佳化(圖片、Suspense 串流)。支援 Claude Code、Cursor、Codex 等 AI 代理工具,可直接引用其規範以生成符合專案慣例的前端程式碼。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/0chan-smc/frontend-dev-guidelines

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

前端開發指南

目的

針對 Next.js 15 與 React 19 的現代前端開發提供全面指南,強調 Server Components、Client Components、App Router 模式、Shadcn/ui 元件、正確的檔案組織方式與效能最佳化。

何時使用此技能

  • 建立新的元件或頁面
  • 建構新功能
  • 擷取資料(Server Components、Server Actions)
  • 使用 Next.js App Router 設定路由
  • 使用 Tailwind CSS 與 Shadcn/ui 設計元件樣式
  • 效能最佳化
  • 組織前端程式碼
  • TypeScript 最佳實踐

快速開始

建立新元件檢查清單

準備建立一個元件?請遵循此檢查清單:

  • 決定 Server Component 還是 Client Component(預設為 Server Component)
  • 只有在需要互動性、鉤子或瀏覽器 API 時才加入 "use client" 指令
  • 使用 TypeScript 搭配明確的 prop 型別
  • 從 @/components/ui 匯入 Shadcn/ui 元件
  • 使用 Tailwind CSS class 進行樣式設計
  • 使用匯入別名:@/components、@/lib、@/hooks
  • 使用 cn() 工具函式處理條件式 class
  • 在檔案底部進行 default export
  • 盡可能使用 Server Components 進行資料擷取

建立新頁面檢查清單

準備建立一個頁面?請設定以下結構:

  • 為路由建立 app/{route-name}/page.tsx
  • 預設使用 Server Component
  • 在 Server Component 中直接擷取資料
  • 為頁面專用元件建立 components/ 目錄
  • 使用 loading.tsx 處理載入狀態
  • 使用 error.tsx 處理錯誤邊界
  • 匯出 metadata 進行 SEO

匯入別名快速參考

別名對應路徑範例
@/專案根目錄import { cn } from '@/lib/utils'
@/componentscomponents/import { Button } from '@/components/ui/button'
@/liblib/import { cn } from '@/lib/utils'
@/hookshooks/import { useMobile } from '@/hooks/use-mobile'
@/appapp/import { Metadata } from 'next'

定義於:tsconfig.json 中的 paths 設定


常用匯入備忘表

// Next.js
import { Metadata } from 'next'
import { Suspense } from 'react'
import { notFound, redirect } from 'next/navigation'

// React(僅限 Client Components)
;('use client')
import { useState, useCallback, useMemo } from 'react'

// Shadcn/ui 元件
import { Button } from '@/components/ui/button'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'

// 工具函式
import { cn } from '@/lib/utils'

// 鉤子(僅限 Client Components)
import { useMobile } from '@/hooks/use-mobile'

// 型別
import type { ComponentProps } from 'react'

主題指南

🎨 元件模式

Server Components 與 Client Components 的比較:

  • Server Components(預設):不需要 "use client",可直接擷取資料,產生的 bundle 較小。
  • Client Components:需要 "use client" 來支援互動性、鉤子及瀏覽器 API。

關鍵概念:

  • 預設使用 Server Components
  • 只在必要時使用 Client Components
  • 使用 Shadcn/ui 元件(它們已經是 Client Components)
  • 元件結構:Props → 資料擷取 → 渲染 → 匯出

Server Component 範例:

// app/features/posts/components/PostList.tsx
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'

interface PostListProps {
  posts: Post[]
}

export function PostList({ posts }: PostListProps) {
  return (
    <div className='grid gap-4'>
      {posts.map((post) => (
        <Card key={post.id}>
          <CardHeader>
            <CardTitle>{post.title}</CardTitle>
          </CardHeader>
          <CardContent>{post.content}</CardContent>
        </Card>
      ))}
    </div>
  )
}

Client Component 範例:

// app/features/posts/components/PostForm.tsx
'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

export function PostForm() {
  const [title, setTitle] = useState('')

  return (
    <form>
      <Input value={title} onChange={(e) => setTitle(e.target.value)} />
      <Button type='submit'>Submit</Button>
    </form>
  )
}

📊 資料擷取

主要模式:Server Components

  • 在 Server Components 中直接擷取資料
  • 在 Server Components 中使用 async/await
  • 無需 useEffect 或外部資料擷取函式庫
  • 自動進行請求去重

Server Actions:

  • 用於處理變更(表單、更新)
  • 建立 app/actions/ 目錄
  • 使用 "use server" 指令標記

包含資料擷取的 Server Component 範例:

// app/posts/page.tsx
import { PostList } from '@/components/PostList'

async function getPosts() {
  const res = await fetch('https://api.example.com/posts', {
    cache: 'no-store', // 或 'force-cache'、'revalidate'
  })
  return res.json()
}

export default async function PostsPage() {
  const posts = await getPosts()

  return <PostList posts={posts} />
}

Server Action 範例:

// app/actions/posts.ts
'use server'

export async function createPost(formData: FormData) {
  const title = formData.get('title')
  // ... 驗證與建立邏輯
  redirect('/posts')
}

📁 檔案組織

App Router 結構:

app/
  (routes)/
    page.tsx          # 路由頁面
    layout.tsx        # 路由佈局
    loading.tsx       # 載入 UI
    error.tsx         # 錯誤 UI
  components/         # 共享元件
    ui/               # Shadcn/ui 元件
  features/           # 功能特定程式碼
    posts/
      components/     # 功能元件
      actions/        # Server Actions
      types/          # TypeScript 型別
lib/
  utils.ts            # 工具函式(cn 等)
hooks/
  use-mobile.ts       # 自訂鉤子(僅限 Client)

功能組織:

  • app/features/{feature}/:功能專用的頁面/路由
  • components/:真正可重複使用的元件
  • components/ui/:Shadcn/ui 元件(請勿直接修改)

🎨 樣式設計

Tailwind CSS + Shadcn/ui:

  • 使用 Tailwind 工具類別
  • 使用 cn() 工具函式處理條件式 class
  • Shadcn/ui 元件使用 CSS 變數進行主題設定
  • 在 app/globals.css 中自訂主題

樣式模式:

import { cn } from '@/lib/utils'

interface ButtonProps {
  variant?: 'primary' | 'secondary'
  className?: string
}

export function Button({ variant = 'primary', className }: ButtonProps) {
  return (
    <button
      className={cn(
        'rounded-md px-4 py-2',
        variant === 'primary' && 'bg-primary text-primary-foreground',
        variant === 'secondary' && 'bg-secondary text-secondary-foreground',
        className,
      )}
    >
      Click me
    </button>
  )
}

Shadcn/ui 元件:

  • 從 @/components/ui/{component-name} 匯入
  • 元件已經過樣式設計且具備無障礙性
  • 可透過 className prop 或 CSS 變數進行自訂

🛣️ 路由

Next.js App Router - 檔案式路由:

  • 目錄:app/{route-name}/page.tsx
  • 巢狀路由:app/{parent}/{child}/page.tsx
  • 動態路由:app/posts/[id]/page.tsx
  • 路由群組:app/(marketing)/about/page.tsx

路由範例:

// app/posts/page.tsx
import { Metadata } from 'next'
import { PostList } from '@/components/PostList'

export const metadata: Metadata = {
  title: 'Posts',
  description: 'List of all posts',
}

export default async function PostsPage() {
  const posts = await getPosts()

  return (
    <div className='container mx-auto py-8'>
      <h1 className='text-3xl font-bold mb-6'>Posts</h1>
      <PostList posts={posts} />
    </div>
  )
}

動態路由:

// app/posts/[id]/page.tsx
interface PostPageProps {
  params: Promise<{ id: string }>
}

export default async function PostPage({ params }: PostPageProps) {
  const { id } = await params
  const post = await getPost(id)

  if (!post) {
    notFound()
  }

  return <PostDetail post={post} />
}

⏳ 載入與錯誤狀態

載入狀態:

  • 在路由目錄中建立 loading.tsx
  • 自動將頁面包覆在 Suspense 中
  • 用於路由層級的載入

錯誤邊界:

  • 在路由目錄中建立 error.tsx
  • 自動捕捉路由中的錯誤
  • 可重設錯誤狀態

載入 UI 範例:

// app/posts/loading.tsx
export default function Loading() {
  return (
    <div className='flex items-center justify-center min-h-screen'>
      <div className='animate-spin rounded-full h-8 w-8 border-b-2 border-primary' />
    </div>
  )
}

錯誤 UI 範例:

// app/posts/error.tsx
'use client'

import { useEffect } from 'react'
import { Button } from '@/components/ui/button'

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  useEffect(() => {
    console.error(error)
  }, [error])

  return (
    <div className='flex flex-col items-center justify-center min-h-screen'>
      <h2 className='text-2xl font-bold mb-4'>Something went wrong!</h2>
      <Button onClick={reset}>Try again</Button>
    </div>
  )
}

⚡ 效能

最佳化模式:

  • 使用 Server Components(較小的 bundle)
  • 使用 next/image 處理圖片
  • 使用 next/font 處理字型
  • 盡可能延遲載入 Client Components
  • 在 Client Components 中使用 useMemo 與 useCallback
  • 使用 Suspense 邊界串流資料

圖片最佳化:

import Image from 'next/image'

export function Avatar({ src, alt }: { src: string; alt: string }) {
  return (
    <Image
      src={src}
      alt={alt}
      width={40}
      height={40}
      className='rounded-full'
    />
  )
}

使用 Suspense 進行串流:

import { Suspense } from 'react'
import { PostList } from '@/components/PostList'
import { Loading } from '@/components/Loading'

export default function Page() {
  return (
    <div>
      <Suspense fallback={<Loading />}>
        <PostList />
      </Suspense>
    </div>
  )
}

📘 TypeScript

標準:

  • 啟用嚴格模式
  • 不使用 any 型別
  • 函式需有明確的回傳型別
  • 型別匯入:import type { Post } from '@/types/post'
  • 元件 prop 介面附帶 JSDoc

範例:

import type { ComponentProps } from 'react'
import { Button } from '@/components/ui/button'

/**
 * 自訂按鈕元件,支援載入狀態
 */
interface CustomButtonProps extends ComponentProps<typeof Button> {
  isLoading?: boolean
}

export function CustomButton({
  isLoading,
  children,
  ...props
}: CustomButtonProps) {
  return (
    <Button disabled={isLoading} {...props}>
      {isLoading ? 'Loading...' : children}
    </Button>
  )
}

🔧 常用模式

表單處理:

  • 使用 Server Actions 處理表單提交
  • 在 Client Components 中使用 react-hook-form 搭配 zod 進行驗證
  • 使用 Shadcn/ui Form 元件

搭配 Server Action 的表單範例:

// app/actions/posts.ts
'use server'

import { z } from 'zod'

const createPostSchema = z.object({
  title: z.string().min(1),
  content: z.string().min(1),
})

export async function createPost(formData: FormData) {
  const rawData = {
    title: formData.get('title'),
    content: formData.get('content'),
  }

  const validated = createPostSchema.parse(rawData)
  // ... 建立文章的邏輯
  redirect('/posts')
}

Metadata:

import { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'Posts',
  description: 'List of all posts',
  openGraph: {
    title: 'Posts',
    description: 'List of all posts',
  },
}

核心原則

  1. 優先使用 Server Components:預設使用 Server Components,只有在必要時才使用 Client Components
  2. App Router 結構:使用 app/ 目錄的檔案式路由
  3. Shadcn/ui 元件:使用預先建立且具備無障礙性的元件
  4. Tailwind CSS:以工具類別為優先的樣式設計,搭配 cn() 輔助函式
  5. TypeScript 嚴格模式:不使用 any,明確指定型別
  6. 效能:使用 Server Components、最佳化圖片、必要時延遲載入
  7. 檔案組織:功能程式碼放在 app/features/,共享元件放在 components/
  8. 匯入別名:使用 @/ 前綴達到乾淨的匯入

快速參考:檔案結構

app/
  layout.tsx                    # 根佈局
  page.tsx                      # 首頁
  globals.css                   # 全域樣式
  (routes)/
    posts/
      page.tsx                  # 文章列表頁面
      [id]/
        page.tsx                # 文章詳細頁面
      loading.tsx               # 載入 UI
      error.tsx                 # 錯誤 UI
  features/
    posts/
      components/
        PostList.tsx            # 功能元件
      actions/
        posts.ts                # Server Actions
components/
  ui/                           # Shadcn/ui 元件
    button.tsx
    card.tsx
lib/
  utils.ts                      # 工具函式(cn 等)
hooks/
  use-mobile.ts                 # 自訂鉤子

現代元件範本(快速複製)

Server Component:

// app/components/PostCard.tsx
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import type { Post } from '@/types/post'

interface PostCardProps {
  post: Post
}

export function PostCard({ post }: PostCardProps) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>{post.title}</CardTitle>
      </CardHeader>
      <CardContent>
        <p>{post.content}</p>
      </CardContent>
    </Card>
  )
}

Client Component:

// app/components/PostForm.tsx
'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

export function PostForm() {
  const [title, setTitle] = useState('')

  return (
    <form>
      <Input value={title} onChange={(e) => setTitle(e.target.value)} />
      <Button type='submit'>Submit</Button>
    </form>
  )
}

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

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

Next.js 16+ uses App Router with Server Components by default. Client Components are only used when interactivity is needed (hooks, event handlers, browser APIs).

ComeOnOliver/skillshub

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

相關技能