資深前端開發
React/Next.js 應用程式的前端開發模式、效能最佳化與自動化工具。
目錄
專案架構
使用 TypeScript、Tailwind CSS 及最佳實踐配置,生成新的 Next.js 或 React 專案。
流程:建立新前端專案
-
使用專案名稱和模板執行架構工具:
python scripts/frontend_scaffolder.py my-app --template nextjs -
加入可選功能(auth、api、forms、testing、storybook):
python scripts/frontend_scaffolder.py dashboard --template nextjs --features auth,api -
進入專案目錄並安裝相依套件:
cd my-app && npm install -
啟動開發伺服器:
npm run dev
架構工具選項
| 選項 | 說明 |
|---|---|
--template nextjs | Next.js 14+ 搭配 App Router 與 Server Components |
--template react | React + Vite 搭配 TypeScript |
--features auth | 加入 NextAuth.js 認證 |
--features api | 加入 React Query + API 客戶端 |
--features forms | 加入 React Hook Form + Zod 驗證 |
--features testing | 加入 Vitest + Testing Library |
--dry-run | 預覽檔案但不實際建立 |
生成的結構(Next.js)
my-app/
├── app/
│ ├── layout.tsx # 根佈局(含字型)
│ ├── page.tsx # 首頁
│ ├── globals.css # Tailwind + CSS 變數
│ └── api/health/route.ts
├── components/
│ ├── ui/ # 按鈕、輸入框、卡片
│ └── layout/ # 標頭、頁尾、側邊欄
├── hooks/ # useDebounce、useLocalStorage
├── lib/ # 工具函式(cn)、常數
├── types/ # TypeScript 介面
├── tailwind.config.ts
├── next.config.js
└── package.json
元件生成
生成具有 TypeScript、測試與 Storybook 故事的 React 元件。
流程:建立新元件
-
生成用戶端元件:
python scripts/component_generator.py Button --dir src/components/ui -
生成伺服器元件:
python scripts/component_generator.py ProductCard --type server -
生成並包含測試與故事檔案:
python scripts/component_generator.py UserProfile --with-test --with-story -
生成自訂 Hook:
python scripts/component_generator.py FormValidation --type hook
生成器選項
| 選項 | 說明 |
|---|---|
--type client | 用戶端元件(含 'use client',預設) |
--type server | 非同步伺服器元件 |
--type hook | 自訂 React Hook |
--with-test | 包含測試檔案 |
--with-story | 包含 Storybook 故事 |
--flat | 在輸出目錄中建立,不另建子目錄 |
--dry-run | 預覽但不實際建立檔案 |
生成的元件範例
'use client';
import { useState } from 'react';
import { cn } from '@/lib/utils';
interface ButtonProps {
className?: string;
children?: React.ReactNode;
}
export function Button({ className, children }: ButtonProps) {
return (
<div className={cn('', className)}>
{children}
</div>
);
}
套件分析
分析 package.json 與專案結構,找出套件最佳化的機會。
流程:最佳化套件大小
-
對你的專案執行分析器:
python scripts/bundle_analyzer.py /path/to/project -
檢視健康分數與問題:
Bundle Health Score: 75/100 (C) HEAVY DEPENDENCIES: moment (290KB) Alternative: date-fns (12KB) or dayjs (2KB) lodash (71KB) Alternative: lodash-es with tree-shaking -
透過取代重型依賴來套用建議的修正。
-
使用詳細模式重新執行,以檢查匯入模式:
python scripts/bundle_analyzer.py . --verbose
套件分數解讀
| 分數 | 等級 | 行動 |
|---|---|---|
| 90-100 | A | 套件已充分最佳化 |
| 80-89 | B | 仍有小幅最佳化空間 |
| 70-79 | C | 應取代重型依賴 |
| 60-69 | D | 多項問題需處理 |
| 0-59 | F | 套件大小存在嚴重問題 |
偵測到的重型依賴
分析器會識別這些常見的厚重套件:
| 套件 | 大小 | 替代方案 |
|---|---|---|
| moment | 290KB | date-fns (12KB) 或 dayjs (2KB) |
| lodash | 71KB | 搭配 tree-shaking 的 lodash-es |
| axios | 14KB | 原生 fetch 或 ky (3KB) |
| jquery | 87KB | 原生 DOM API |
| @mui/material | 較大 | shadcn/ui 或 Radix UI |
React 模式
參考資料:references/react_patterns.md
複合元件
在相關元件之間共用狀態:
const Tabs = ({ children }) => {
const [active, setActive] = useState(0);
return (
<TabsContext.Provider value={{ active, setActive }}>
{children}
</TabsContext.Provider>
);
};
Tabs.List = TabList;
Tabs.Panel = TabPanel;
// 使用方式
<Tabs>
<Tabs.List>
<Tabs.Tab>One</Tabs.Tab>
<Tabs.Tab>Two</Tabs.Tab>
</Tabs.List>
<Tabs.Panel>Content 1</Tabs.Panel>
<Tabs.Panel>Content 2</Tabs.Panel>
</Tabs>
自訂 Hook
提取可重複使用的邏輯:
function useDebounce<T>(value: T, delay = 500): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
// 使用方式
const debouncedSearch = useDebounce(searchTerm, 300);
Render Props
共用渲染邏輯:
function DataFetcher({ url, render }) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
}, [url]);
return render({ data, loading });
}
// 使用方式
<DataFetcher
url="/api/users"
render={({ data, loading }) =>
loading ? <Spinner /> : <UserList users={data} />
}
/>
Next.js 最佳化
參考資料:references/nextjs_optimization_guide.md
伺服器 vs 用戶端元件
預設使用 Server Components。僅在需要以下功能時才加入 'use client':
- 事件處理器(onClick、onChange)
- 狀態(useState、useReducer)
- 副作用(useEffect)
- 瀏覽器 API
// Server Component(預設)- 無 'use client'
async function ProductPage({ params }) {
const product = await getProduct(params.id); // 伺服器端擷取
return (
<div>
<h1>{product.name}</h1>
<AddToCartButton productId={product.id} /> {/* 用戶端元件 */}
</div>
);
}
// Client Component
'use client';
function AddToCartButton({ productId }) {
const [adding, setAdding] = useState(false);
return <button onClick={() => addToCart(productId)}>Add</button>;
}
圖片最佳化
import Image from 'next/image';
// 首屏以上 - 立即載入
<Image
src="/hero.jpg"
alt="Hero"
width={1200}
height={600}
priority
/>
// 響應式圖片使用 fill
<div className="relative aspect-video">
<Image
src="/product.jpg"
alt="Product"
fill
sizes="(max-width: 768px) 100vw, 50vw"
className="object-cover"
/>
</div>
資料擷取模式
// 平行擷取
async function Dashboard() {
const [user, stats] = await Promise.all([
getUser(),
getStats()
]);
return <div>...</div>;
}
// 使用 Suspense 串流
async function ProductPage({ params }) {
return (
<div>
<ProductDetails id={params.id} />
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews productId={params.id} />
</Suspense>
</div>
);
}
無障礙與測試
參考資料:references/frontend_best_practices.md
無障礙檢查清單
- 語意化 HTML:使用適當的元素(
<button>、<nav>、<main>) - 鍵盤導航:所有互動元素皆可聚焦
- ARIA 標籤:為圖示與複雜小工具提供標籤
- 色彩對比:一般文字最低 4.5:1
- 焦點指示器:可見的焦點狀態
// 無障礙按鈕
<button
type="button"
aria-label="關閉對話框"
onClick={onClose}
className="focus-visible:ring-2 focus-visible:ring-blue-500"
>
<XIcon aria-hidden="true" />
</button>
// 為鍵盤使用者提供的跳過連結
<a href="#main-content" className="sr-only focus:not-sr-only">
跳至主要內容
</a>
測試策略
// 使用 React Testing Library 的元件測試
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('按鈕點擊觸發動作', async () => {
const onClick = vi.fn();
render(<Button onClick={onClick}>Click me</Button>);
await userEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalledTimes(1);
});
// 測試無障礙
測試('對話框具備無障礙性', async () => {
render(<Dialog open={true} title="確認" />);
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('dialog')).toHaveAttribute('aria-labelledby');
});
快速參考
常見 Next.js 配置
// next.config.js
const nextConfig = {
images: {
remotePatterns: [{ hostname: "cdnexamplecom" }],
formats: ['image/avif', 'image/webp'],
},
experimental: {
optimizePackageImports: ['lucide-react', '@heroicons/react'],
},
};
Tailwind CSS 工具函式
// 使用 cn() 的條件式類別
import { cn } from '@/lib/utils';
<button className={cn(
'px-4 py-2 rounded',
variant === 'primary' && 'bg-blue-500 text-white',
disabled && 'opacity-50 cursor-not-allowed'
)} />
TypeScript 模式
// 含 children 的 Props
interface CardProps {
className?: string;
children: React.ReactNode;
}
// 泛型元件
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map(renderItem)}</ul>;
}
資源
- React 模式:
references/react_patterns.md - Next.js 最佳化:
references/nextjs_optimization_guide.md - 最佳實踐:
references/frontend_best_practices.md - 強制提問庫(Matt Pocock 的 grill):
references/forcing_questions.md - 組合圖(應分派給哪個專家):
references/composition_map.md
假設與可驗證的成功標準(Karpathy 紀律)
在此技能生成元件、建議框架或稽核套件之前,必須先明確以下四項假設。
- 主要使用者裝置 + 網路 — mobile-4G、desktop-fiber、low-end-Android 或 corporate-network。影響所有效能決策。
- LCP 目標(毫秒) — 單一數字,而非「快速」。決定套件預算與渲染方式的選擇。
- 是否依賴 SEO 或需認證 — 影響渲染方式(SSR/SSG/RSC 與 SPA)。
- WCAG 目標 + 指定的無障礙負責人 — AA、AAA 或盡力而為。影響無障礙投資與 CI 閘門。
可驗證的成功標準(Karpathy #4)— 每項建議都必須包含:
- 在主要裝置上 p75 的 Core Web Vitals 目標(LCP、INP、CLS)
- 每路由 KB-gzip 的 JS 套件預算
- Lighthouse 無障礙最低分數 + 效能最低分數
如果其中任何一項未說明,則該建議不完整 — 返回強制提問庫的 Q2。
scripts/frontend_decision_engine.py 工具內建了這些檢查:若沒有提供四項假設輸入,它會拒絕建議設定檔,並為匹配的設定檔印出可驗證的門檻值。
自訂設定檔
profiles/ 中的四個內建設定檔可校準每項建議:
| 設定檔 | 何時選用 | 手機 4G p75 的 LCP 目標 | 套件預算 |
|---|---|---|---|
next-app-router | SaaS 客戶端應用、需要 SEO 與動態功能、以 RSC 優先 | 2000ms | 150 KB-gzip / 路由 |
remix-or-sveltekit | 主要使用手機 4G、低 JS 優先、漸進增強 | 1500ms | 80 KB-gzip / 路由 |
vite-spa | 需認證的應用、主要使用桌上型/企業網路 | 2500ms | 200 KB 初始 + 80 KB / 路由 |
astro-or-static | 行銷/文件/部落格、近乎零寫入、對 SEO 至關重要 | 1200ms | 30 KB JS / 頁面 |
透過下列指令選取設定檔:
python scripts/frontend_decision_engine.py \
--primary-device mobile-4g --lcp-target-ms 2000 \
--seo-dependent true --auth-walled false --team-size 5
該工具會回傳最適設定檔、差距在 15% 內的次佳方案、技術棧選擇、該設定檔應避免的反模式,以及所需的 CI 閘門。
若要新增自訂設定檔(例如,你組織的內部工具預設值):複製 profiles/vite-spa.json 到 profiles/<你的組織名稱>.json,並調整 constraints 與 success_thresholds。
組合圖
此技能不會重新實作屬於強大專家等級的範疇;而是分派給它們。完整的路由表請見 references/composition_map.md。主要的分派目標:
| 關注領域 | 分派至 |
|---|---|
| WCAG 稽核、對比度、螢幕閱讀器 | engineering-team/skills/a11y-audit/ |
| 套件分析與執行時期效能 | engineering/skills/performance-profiler/ |
| 電影級/滾動敘事登陸頁面 | engineering-team/skills/epic-design/ |
| Apple 人機介面指南(iOS / macOS / visionOS) | product-team/skills/apple-hig-expert/ |
| 提交前的 Karpathy 審查 | engineering/karpathy-coder/ |
| 預先架構拷問 | engineering/grill-me/ |
cs-frontend-engineer 代理會透過 context: fork 協調這些分派。若要從其他代理呼叫它:Agent({subagent_type: "cs-frontend-engineer", prompt: "..."}) 或透過 /cs:frontend-rev 使用。