DevLog
Next.js性能优化

Next.js 应用性能优化实战:从 Core Web Vitals 到极致体验

2025-10-20·15

背景

我们的 Next.js 应用在上线初期遇到了严重的性能问题:

- LCP(最大内容绘制): 4.2s(远超 2.5s 的良好标准)

- FID(首次输入延迟): 280ms

- CLS(累积布局偏移): 0.18

经过两周的系统优化,最终达到了:

- LCP: 1.1s

- FID: 45ms

- CLS: 0.02

优化一:图片优化

使用 next/image

import Image from 'next/image';

// 之前

<img src="/hero.jpg" alt="Hero" />

// 之后

<Image

src="/hero.jpg"

alt="Hero"

width={1200}

height={600}

priority // LCP 图片加 priority

sizes="(max-width: 768px) 100vw, 1200px"

/>

图片格式转换

将 PNG/JPG 转换为 WebP/AVIF 格式,文件大小减少 30-60%:

# 使用 sharp 批量转换

npx sharp-cli --input "public/images/*.png" --output "public/images/" --format webp

优化二:字体加载

import { Inter } from 'next/font/google';

const inter = Inter({

subsets: ['latin'],

display: 'swap', // 防止 FOIT

preload: true,

});

优化三:代码分割

import dynamic from 'next/dynamic';

// 懒加载重型组件

const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {

ssr: false,

loading: () => <ChartSkeleton />,

});

优化四:缓存策略

// app/api/posts/route.ts

export async function GET() {

const posts = await fetchPosts();

return Response.json(posts, {

headers: {

'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',

},

});

}

总结

性能优化是一个系统工程,需要从多个维度协同发力。建议使用 Lighthouse CI 在 CD 流程中持续监控,防止性能退化。

返回文章列表