1. 核心網路生命線
| 公制 | 描述 | 好 | 如何改進 |
|---|---|---|---|
| 液晶聚合物 | 最大的內容塗料 | < 2.5秒 | 優先圖像、預載字體 |
| 內啡肽 | 與下一個繪畫的交互 | <200毫秒 | 減少 JS,使用過渡 |
| CLS | 累積佈局偏移 | < 0.1 | 設定圖像大小,避免 FOUT |
2. 動態導入和程式碼分割
import dynamic from 'next/dynamic';
// Lazy load heavy component
const CodeEditor = dynamic(() => import('@/components/CodeEditor'), {
loading: () => <div>Loading editor...</div>,
ssr: false, // Client-only component
});
// Conditional dynamic import
const AdminPanel = dynamic(() => import('@/components/AdminPanel'));
export default function Page({ isAdmin }: { isAdmin: boolean }) {
return (
<div>
<CodeEditor />
{isAdmin && <AdminPanel />}
</div>
);
}
3. 記憶模式
import { memo, useMemo, useCallback } from 'react';
// memo — skip re-render if props unchanged
const ExpensiveList = memo(function ExpensiveList({ items }: { items: Item[] }) {
return (
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
);
});
// useMemo — cache expensive computation
function Dashboard({ data }: { data: number[] }) {
const stats = useMemo(() => ({
total: data.reduce((a, b) => a + b, 0),
average: data.reduce((a, b) => a + b, 0) / data.length,
max: Math.max(...data),
}), [data]);
return <div>Total: {stats.total}</div>;
}
// useCallback — stable function reference
function Parent() {
const handleClick = useCallback((id: string) => {
console.log('Clicked:', id);
}, []);
return <ExpensiveChild onClick={handleClick} />;
}
4. 捆綁分析
npm install -D @next/bundle-analyzer
// next.config.ts
import withBundleAnalyzer from '@next/bundle-analyzer';
const config = withBundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})({
// ...other config
});
export default config;
# Analyze bundle
ANALYZE=true npm run build
5. 字體優化
// app/layout.tsx
import { Inter, JetBrains_Mono } from 'next/font/google';
const inter = Inter({
subsets: ['latin', 'vietnamese'],
display: 'swap',
variable: '--font-inter',
});
const mono = JetBrains_Mono({
subsets: ['latin'],
display: 'swap',
variable: '--font-mono',
});
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="vi" className={`${inter.variable} ${mono.variable}`}>
<body className="font-sans">{children}</body>
</html>
);
}
6. 快取標頭
// next.config.ts
const config = {
async headers() {
return [
{
source: '/images/:path*',
headers: [
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
],
},
{
source: '/api/:path*',
headers: [
{ key: 'Cache-Control', value: 'public, s-maxage=60, stale-while-revalidate=300' },
],
},
];
},
};
7.React編譯器(實驗)
// next.config.ts
const config = {
experimental: {
reactCompiler: true, // Auto-memoize components
},
};
下一篇: Docker 和 CI/CD — 容器化、GitHub Actions、Vercel 部署。