Next.js 性能优化实战
性能优化是现代 Web 应用的核心要求。本文将分享 Next.js 应用性能优化的最佳实践。
代码分割与懒加载
使用动态导入实现组件级别的代码分割:
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(() => import('../components/HeavyComponent'), {
loading: () => <p>Loading...</p>,
ssr: false // 禁用服务端渲染
});
export default function Page() {
return (
<div>
<h1>My Page</h1>
<DynamicComponent />
</div>
);
}
图片优化
Next.js Image 组件的最佳实践:
import Image from 'next/image';
export default function OptimizedImage() {
return (
<Image
src="/hero-image.jpg"
alt="Hero"
width={800}
height={600}
priority // 关键图片优先加载
placeholder="blur"
blurDataURL="data:image/jpeg;base64,..."
/>
);
}
字体优化
使用 next/font 优化字体加载:
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter'
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={inter.variable}>
<body>{children}</body>
</html>
);
}
缓存策略
配置适当的缓存头:
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{
key: 'Cache-Control',
value: 's-maxage=60, stale-while-revalidate=300'
}
]
}
];
}
};
总结
通过合理的代码分割、图片优化、字体优化和缓存策略,可以显著提升 Next.js 应用的性能表现。