mcpField
N
nextjs-optimization

nextjs-optimization

github.com/atman36开发678 次安装40 周前更新
代码仓库

关于 nextjs-optimization

用于检查和优化 Next.js 应用的技能,涵盖渲染、数据获取、缓存、代码包、SEO 和 Core Web Vitals,适用于开发及部署前的改进工作。

主要功能

  1. 01渲染策略指导
  2. 02图像与代码包优化
  3. 03数据获取与缓存
  4. 04元数据和 SEO 检查
  5. 05Lighthouse 与 Web Vitals 指导

适用场景

  1. 01部署前检查 Next.js 应用
  2. 02排查页面加载缓慢
  3. 03改进缓存与数据获取

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/atman36/ai-vibe-prompts --skill nextjs-optimization

安装后在 Claude Code 中输入/nextjs-optimization确认已加载。

详细介绍

Next.js 15 优化技能

目标

优化 Next.js 应用,实现:

  • Core Web Vitals 得分达到满分(LCP < 2.5s,FID < 100ms,CLS < 0.1)
  • 页面快速加载并采用最优渲染策略
  • 高效的数据获取与缓存
  • 可用于生产环境的构建配置
  • 卓越的 SEO 与无障碍体验

何时使用此技能

在以下情况下自动调用:

  • 项目使用 Next.js(检测到依赖中包含 next)
  • 用户提到“优化”“性能”“缓慢”或“Core Web Vitals”
  • 部署到生产环境之前
  • 添加新功能或页面之后
  • 用户要求进行 Next.js 专属改进

前置条件检查

工具:Read、Grep

  1. 验证 Next.js 版本:

    # Read package.json
    # Check for "next": "^15.0.0" or higher
    
  2. 检测 App Router(Next.js 13+):

    • 检查是否存在 app/ 目录
    • 检查是否存在 layout.tsx、page.tsx 文件
  3. 检测 Pages Router(旧版):

    • 检查是否存在 pages/ 目录
    • 建议迁移到 App Router

优化类别

1. 渲染策略优化

目标:为每个页面/组件选择最优渲染方式

工具:Read、Grep、Edit

1.1 服务端组件(App Router 中的默认方式)

适用场景:

  • 从 API/数据库获取数据
  • 密集计算
  • 访问后端资源

模式:

// app/dashboard/page.tsx
export default async function DashboardPage() {
  const data = await fetchData(); // Runs on server
  return <Dashboard data={data} />;
}

检查违规用法:

# Search for "use client" in components that don't need it
grep -r "use client" app/ | grep -v "onClick\|useState\|useEffect"
1.2 客户端组件

适用场景:

  • 交互式 UI(onClick、表单)
  • 浏览器 API(window、localStorage)
  • React Hooks(useState、useEffect)

模式:

// app/components/Counter.tsx
'use client';

export default function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

优化:保持客户端组件小巧,并将其作为叶节点

1.3 静态生成(SSG)

适用场景:

  • 内容很少变更
  • 营销页面、博客、文档

模式:

export const revalidate = 3600; // Revalidate every hour

export default async function BlogPost({ params }) {
  const post = await getPost(params.slug);
  return <Article post={post} />;
}
1.4 使用 ISR 的动态渲染

适用场景:

  • 定期变更的内容
  • 电商产品、用户个人资料

模式:

export const revalidate = 60; // Revalidate every minute

export async function generateStaticParams() {
  const products = await getProducts();
  return products.map((p) => ({ slug: p.slug }));
}
2. 图像优化

目标:优化图像性能和 Core Web Vitals 指标

工具:Grep、Read、Edit

2.1 使用 Next.js Image 组件

查找未优化的图像:

grep -rn "<img " app/ src/

替换为:

import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero image"
  width={1200}
  height={600}
  priority // For above-the-fold images
  placeholder="blur" // Optional blur-up effect
/>
2.2 配置图像域名

读取 next.config.js:

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
      },
    ],
    formats: ['image/avif', 'image/webp'], // Modern formats
  },
};
2.3 懒加载策略
  • priority:首屏图像(LCP 候选项)
  • loading="lazy":非首屏图像(默认)
3. 字体优化

目标:消除 FOUT/FOIT 并改善字体加载

工具:Read、Edit

3.1 使用 next/font

模式:

// app/layout.tsx
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  display: 'swap', // Prevent FOIT
  variable: '--font-inter',
});

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={inter.variable}>
      <body>{children}</body>
    </html>
  );
}
3.2 自托管字体
import localFont from 'next/font/local';

const customFont = localFont({
  src: './fonts/CustomFont.woff2',
  display: 'swap',
  variable: '--font-custom',
});
4. 数据获取优化

目标:减少请求瀑布并优化缓存

工具:Read、Grep、Edit

4.1 并行获取数据

反模式(顺序执行):

const user = await getUser();
const posts = await getPosts(user.id); // Waits for user

优化后(并行执行):

const [user, posts] = await Promise.all([
  getUser(),
  getPosts(),
]);
4.2 使用 Suspense 实现流式传输

模式:

import { Suspense } from 'react';

export default function Page() {
  return (
    <>
      <Header />
      <Suspense fallback={<Skeleton />}>
        <SlowComponent />
      </Suspense>
      <Footer />
    </>
  );
}
4.3 缓存配置
// Aggressive caching
fetch('https://api.example.com/data', {
  next: { revalidate: 3600 }, // Cache for 1 hour
});

// No caching
fetch('https://api.example.com/data', {
  cache: 'no-store', // Always fresh
});

// Opt out of caching
export const dynamic = 'force-dynamic';
5. Bundle 优化

目标:减小 JavaScript Bundle 的体积

工具:Bash、Read、Edit

5.1 分析 Bundle
# Add to package.json scripts
npm run build
npx @next/bundle-analyzer
5.2 动态导入

查找大型组件:

find app -name "*.tsx" -exec wc -l {} \; | sort -rn | head -10

使用动态导入进行拆分:

import dynamic from 'next/dynamic';

const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
  loading: () => <Skeleton />,
  ssr: false, // Skip SSR if not needed
});
5.3 Tree Shaking

检查是否使用 barrel 导出:

grep -rn "export \* from" app/

替换为指定导入:

// Anti-pattern
import { Button, Card, Modal } from '@/components';

// Optimized
import { Button } from '@/components/Button';
6. 元数据与 SEO

目标:实现最佳 SEO 和社交分享效果

工具:Read、Edit

6.1 静态元数据
// app/layout.tsx
export const metadata = {
  title: {
    default: 'My App',
    template: '%s | My App',
  },
  description: 'Description for SEO',
  openGraph: {
    title: 'My App',
    description: 'Description for social sharing',
    images: ['/og-image.jpg'],
  },
  twitter: {
    card: 'summary_large_image',
  },
};
6.2 动态元数据
export async function generateMetadata({ params }) {
  const post = await getPost(params.slug);
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      images: [post.ogImage],
    },
  };
}
7. 生产环境配置

目标:针对生产环境优化 next.config.js

工具:Read、Edit

7.1 基本配置
// next.config.js
module.exports = {
  reactStrictMode: true,
  poweredByHeader: false, // Security
  compress: true, // Gzip compression
  
  // Compiler optimizations
  compiler: {
    removeConsole: process.env.NODE_ENV === 'production',
  },
  
  // Image optimization
  images: {
    formats: ['image/avif', 'image/webp'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920],
  },
  
  // React Compiler (Next.js 15)
  experimental: {
    reactCompiler: true,
  },
};
7.2 Turbopack(开发环境)
// package.json
{
  "scripts": {
    "dev": "next dev --turbo"
  }
}
8. Core Web Vitals 优化

目标:获得满分 Lighthouse 评分

工具:Bash、Grep、Edit

8.1 LCP(最大内容绘制)< 2.5s

优化方式:

  • 为主视觉图像使用 priority
  • 预加载关键资源
  • 服务端渲染首屏内容
// Preload critical resources
<link rel="preload" href="/hero.jpg" as="image" />
8.2 FID(首次输入延迟)< 100ms

优化方式:

  • 尽量减少 JavaScript 执行
  • 对非关键代码使用动态导入
  • 延迟加载第三方脚本
import Script from 'next/script';

<Script
  src="https://analytics.example.com"
  strategy="lazyOnload" // Load after page interactive
/>
8.3 CLS(累积布局偏移)< 0.1

优化:

  • 始终指定图片尺寸
  • 为动态内容预留空间
  • 使用 font-display: swap
/* Reserve space for ads/banners */
.ad-container {
  min-height: 250px;
}
9. 缓存策略

目标:最大限度地提高缓存命中率并尽量减少服务器负载

工具:Read、Edit

9.1 路由段配置
// app/dashboard/page.tsx
export const revalidate = 3600; // ISR every hour
export const dynamic = 'auto'; // Automatic optimization
export const fetchCache = 'force-cache'; // Aggressive caching
9.2 数据缓存
// Deduplicated and cached automatically
const user = await fetch('https://api.example.com/user');

// Revalidate tag-based
export const revalidate = 60;
export const tags = ['user', 'profile'];
10. 监控与测量

目标:持续追踪性能

工具:Bash、WebSearch

10.1 添加 Web Vitals 报告
// app/layout.tsx
import { SpeedInsights } from '@vercel/speed-insights/next';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <SpeedInsights />
      </body>
    </html>
  );
}
10.2 Lighthouse CI
# Run Lighthouse
npx lighthouse http://localhost:3000 --view

# Check Core Web Vitals
npm run build
npm run start
npx lighthouse http://localhost:3000 --only-categories=performance

优化检查清单

逐项检查以下内容:

  • 所有图片均使用 next/image,并设置了合适的尺寸
  • 字体使用 next/font,并设置 display: swap
  • 默认使用服务器组件(不必要时不使用 'use client')
  • 客户端组件是叶节点,且数量尽可能少
  • 尽可能使用并行请求获取数据
  • 使用 <Suspense> 包裹缓慢的组件
  • 大型组件使用动态导入
  • 为所有页面配置元数据
  • next.config.js 已启用生产环境优化
  • 已启用 React Compiler(Next.js 15)
  • 已分析并优化打包内容
  • Core Web Vitals 达到目标(使用 Lighthouse 测试)

输出格式

# Next.js Optimization Report

## Current Status
- **Next.js Version**: 15.0.3
- **Rendering**: App Router
- **React Version**: 19.0.0

## Issues Found

### 🔴 Critical (3)
1. **Unoptimized Images**: 12 `<img>` tags found
   - Files: `app/page.tsx`, `app/about/page.tsx`
   - Fix: Replace with `next/image`

2. **Large Client Bundle**: 342 KB (target: < 200 KB)
   - Cause: Heavy chart library loaded synchronously
   - Fix: Use dynamic import for `Chart` component

3. **Missing Font Optimization**: Using Google Fonts via <link>
   - Fix: Migrate to `next/font/google`

### 🟡 Warnings (2)
1. **Sequential Data Fetching**: Waterfall detected in `app/dashboard/page.tsx`
2. **No Metadata**: Missing OpenGraph tags on 5 pages

## Optimizations Applied

✅ Enabled React Compiler in next.config.js
✅ Added image optimization config
✅ Configured proper cache headers
✅ Added Suspense boundaries to slow routes

## Performance Impact (Estimated)

- **Load Time**: 3.2s → 1.8s (-44%)
- **Bundle Size**: 342 KB → 198 KB (-42%)
- **LCP**: 3.1s → 2.3s (✅ Good)
- **FID**: 85ms → 45ms (✅ Good)
- **CLS**: 0.15 → 0.05 (✅ Good)

## Next Steps

1. Replace 12 `<img>` tags with `next/image`
2. Split Chart component with dynamic import
3. Add metadata to 5 pages
4. Run Lighthouse to verify improvements

最佳实践

  1. 服务端优先:默认使用服务器组件
  2. 渐进增强:优先针对慢速网络构建
  3. 测量而非猜测:使用 Lighthouse 和 Web Vitals
  4. 积极缓存:但要适时重新验证
  5. 逐步优化:优先修复关键问题

与其他技能集成

  • codebase-analysis - 检测 Next.js 项目及其版本
  • quality-gates - 运行构建并确认没有回归
  • react-patterns - 确保遵循 React 19 最佳实践
  • testing-strategy - 添加性能测试

应避免的常见反模式

❌ 在顶层使用 'use client' ❌ 未指定图片尺寸 ❌ 同步获取数据 ❌ 加载完整的组件库 ❌ 没有 Suspense 边界 ❌ 忽略 Core Web Vitals

版本历史

  • 1.0.0(2025-01-03):面向 Next.js 15、重点关注 App Router 的初始技能

评论

支持 Markdown