前端開發指南
目的
針對 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' |
@/components | components/ | import { Button } from '@/components/ui/button' |
@/lib | lib/ | import { cn } from '@/lib/utils' |
@/hooks | hooks/ | import { useMobile } from '@/hooks/use-mobile' |
@/app | app/ | 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}匯入 - 元件已經過樣式設計且具備無障礙性
- 可透過
classNameprop 或 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',
},
}
核心原則
- 優先使用 Server Components:預設使用 Server Components,只有在必要時才使用 Client Components
- App Router 結構:使用
app/目錄的檔案式路由 - Shadcn/ui 元件:使用預先建立且具備無障礙性的元件
- Tailwind CSS:以工具類別為優先的樣式設計,搭配
cn()輔助函式 - TypeScript 嚴格模式:不使用
any,明確指定型別 - 效能:使用 Server Components、最佳化圖片、必要時延遲載入
- 檔案組織:功能程式碼放在
app/features/,共享元件放在components/ - 匯入別名:使用
@/前綴達到乾淨的匯入
快速參考:檔案結構
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>
)
}