← 返回笔记列表
·10 分钟阅读

Next.js 学习笔记

Next.js App Router、渲染模式与 SEO 优化的个人学习记录。

  • Next.js
  • React
  • 前端

Next.js 学习笔记

概述

Next.js 是基于 React 的全栈框架,由 Vercel 维护。最近用它重构了个人博客,体验非常好。特别是 App Router 和 Server Components,确实解决了很多传统 React 开发的痛点。

核心优势

  • App Router:基于文件系统的路由与布局,结构更清晰
  • 多种渲染模式:SSG、SSR、ISR、CSR 灵活选择
  • SEO 友好:服务端生成 HTML,元数据配置简单
  • 部署方便:与 Vercel 深度集成,零配置部署
  • 全栈能力:API Route、Server Action、数据库访问

App Router 基础

目录结构

src/app/
  layout.tsx        # 根布局
  page.tsx          # 首页 /
  loading.tsx       # 加载态(全局)
  error.tsx         # 错误处理(全局)
  not-found.tsx     # 404 页面
  notes/
    page.tsx        # /notes
    [slug]/
      page.tsx      # /notes/:slug
      loading.tsx   # 笔记详情页加载态
      error.tsx     # 笔记详情页错误处理
  sitemap.ts        # 自动生成 sitemap
  robots.ts         # robots.txt

页面与布局

  • page.tsx:路由页面,导出默认组件
  • layout.tsx:共享布局,可嵌套,接收 children
  • loading.tsx:加载态,自动 Suspense
  • not-found.tsx:404 页面,调用 notFound() 触发
  • error.tsx:错误边界,捕获子组件错误

Server Component vs Client Component

默认是 Server Component,适合:

  • 直接访问数据库
  • 读取文件系统
  • 调用外部 API
  • 减少客户端 JS 体积

需要交互时使用 "use client":

'use client';

import { useState, useEffect } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);
  const [data, setData] = useState(null);

  useEffect(() => {
    // 客户端数据获取
    fetch('/api/data').then(res => res.json()).then(setData);
  }, []);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>{count}</button>
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
}

注意事项:

  • Server Component 不能使用 useState、useEffect 等 React hooks
  • Client Component 可以导入 Server Component,但反之不行
  • 第三方库需要注意是否支持 Server Component

数据获取

在 Server Component 中

export default async function NotesPage() {
  const notes = await getNotes();
  
  return (
    <ul>
      {notes.map((note) => (
        <li key={note.id}>{note.title}</li>
      ))}
    </ul>
  );
}

优势:

  • 数据在服务端获取,首屏更快
  • 可以直接访问数据库,无需 API 层
  • 不会暴露敏感信息(如 API Key)

静态生成(SSG)

export async function generateStaticParams() {
  const slugs = await getNoteSlugs();
  return slugs.map((slug) => ({ slug }));
}

export default async function NotePage({ params }) {
  const note = await getNoteBySlug(params.slug);
  return <article>{note.content}</article>;
}

构建时预渲染所有笔记详情页,有利于 SEO 和性能。适合内容不经常变化的页面。

增量静态再生(ISR)

export const revalidate = 60; // 每 60 秒重新生成

export default async function BlogPage() {
  const posts = await fetchPosts();
  return <PostList posts={posts} />;
}

适用场景:

  • 内容需要更新,但不需要实时更新
  • 页面访问量大,全量重新构建成本高
  • 如博客文章、新闻列表

Server Action

Next.js 13+ 引入的新特性,允许在组件中直接定义服务端函数。

'use server';

export async function createNote(formData: FormData) {
  const title = formData.get('title') as string;
  const content = formData.get('content') as string;
  
  await db.note.create({
    data: { title, content },
  });
}

在客户端组件中使用:

'use client';

import { createNote } from './actions';

export function NoteForm() {
  return (
    <form action={createNote}>
      <input type="text" name="title" placeholder="标题" />
      <textarea name="content" placeholder="内容" />
      <button type="submit">创建</button>
    </form>
  );
}

优势:

  • 无需单独创建 API Route
  • 自动 CSRF 保护
  • 可以直接访问数据库
  • 支持流式响应

SEO 配置

页面 metadata

import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: '笔记',
  description: '技术学习笔记列表',
  alternates: {
    canonical: 'https://example.com/notes',
  },
  openGraph: {
    title: '笔记',
    description: '技术学习笔记列表',
    type: 'website',
    images: '/og-image.png',
  },
  twitter: {
    card: 'summary_large_image',
    title: '笔记',
    description: '技术学习笔记列表',
  },
};

动态 metadata

export async function generateMetadata({ params }) {
  const note = await getNoteBySlug(params.slug);
  
  return {
    title: note.title,
    description: note.excerpt || note.content.slice(0, 150),
    openGraph: {
      title: note.title,
      description: note.excerpt,
      images: note.coverImage || '/og-image.png',
    },
  };
}

JSON-LD 结构化数据

帮助搜索引擎理解页面内容。

import { JsonLd } from 'next-seo';

export function NoteJsonLd({ note }) {
  return (
    <JsonLd
      data={{
        '@context': 'https://schema.org',
        '@type': 'Article',
        headline: note.title,
        description: note.excerpt,
        author: {
          '@type': 'Person',
          name: '作者名',
        },
        datePublished: note.createdAt,
        dateModified: note.updatedAt,
      }}
    />
  );
}

样式方案

Tailwind CSS

<h1 className="text-4xl font-semibold text-white">标题</h1>
<p className="mt-4 text-neutral-400">正文内容</p>

CSS Modules

import styles from './NoteCard.module.css';

export function NoteCard({ note }) {
  return (
    <div className={styles.card}>
      <h3 className={styles.title}>{note.title}</h3>
    </div>
  );
}

全局样式

在 app/globals.css 中定义:

* {
  box-sizing: border-box;
}

body {
  font-family: var(--font-sans);
  background-color: #0a0a0a;
  color: #e5e5e5;
}

路由系统

动态路由

notes/[slug]/page.tsx → /notes/nextjs
notes/[...slug]/page.tsx → /notes/a/b/c (可选捕获)
notes/[[...slug]]/page.tsx → /notes 或 /notes/a/b/c (可选捕获)

路由组

(marketing)/
  page.tsx      → /
  about/
    page.tsx    → /about
(admin)/
  dashboard/
    page.tsx    → /dashboard

路由组不会影响 URL 路径,用于组织相关页面。

并行路由

// app/layout.tsx
export default function RootLayout({
  children,
  sidebar,
}: {
  children: React.ReactNode;
  sidebar: React.ReactNode;
}) {
  return (
    <div className="flex">
      <div className="w-64">{sidebar}</div>
      <main className="flex-1">{children}</main>
    </div>
  );
}

创建 app/@sidebar 目录来定义并行路由内容。

与 Supabase 配合

典型博客架构:

Next.js (Vercel)     →  前端 + SSR/SSG
Supabase PostgreSQL  →  文章元数据(Prisma)
Supabase Storage     →  Markdown 文件
Supabase Auth        →  用户认证

流程:

  1. Prisma 从数据库读取 title、slug、storagePath
  2. 从 Storage 下载 .md 文件
  3. 用 react-markdown 渲染
  4. 用户认证使用 Supabase Auth

Prisma 配置

model Note {
  id          String   @id @default(cuid())
  title       String
  slug        String   @unique
  content     String
  excerpt     String?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function getNotes() {
  return await prisma.note.findMany({
    orderBy: { createdAt: 'desc' },
  });
}

性能优化

图片优化

import Image from 'next/image';

<Image
  src="/hero.png"
  alt="Hero"
  width={1200}
  height={600}
  priority // 首屏图片优先加载
/>

Next.js 会自动:

  • 生成多种尺寸的图片
  • 支持 WebP/AVIF 格式
  • 懒加载(默认)
  • 响应式调整

代码分割

Next.js 自动按路由分割代码,只加载当前页面需要的 JavaScript。

缓存策略

export const revalidate = 3600; // 1 小时

// 或在 fetch 中指定
const res = await fetch(url, {
  next: { revalidate: 60 },
});

字体优化

import { Noto_Sans_SC, JetBrains_Mono } from 'next/font/google';

const sans = Noto_Sans_SC({
  variable: '--font-sans',
  subsets: ['latin'],
  display: 'swap',
});

const mono = JetBrains_Mono({
  variable: '--font-mono',
  subsets: ['latin'],
  display: 'swap',
});

开发技巧

环境变量

# .env.local
DATABASE_URL="postgresql://..."
SUPABASE_URL="https://..."
SUPABASE_SERVICE_ROLE_KEY="..."

前缀为 NEXT_PUBLIC_ 的变量会暴露给客户端。

路径别名

在 tsconfig.json 中配置:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

使用:

import { cn } from '@/lib/utils';
import { NoteCard } from '@/components/NoteCard';

常用命令

npm run dev      # 本地开发
npm run build    # 生产构建
npm run start    # 启动生产服务
npm run lint     # 代码检查

部署

Vercel(推荐)

  1. 连接 GitHub 仓库
  2. Vercel 自动检测 Next.js 项目
  3. 配置环境变量
  4. 一键部署

Docker

FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3000

CMD ["npm", "start"]

学习要点总结

主题说明
App Router文件路由 + 布局 + 嵌套
Server Component默认,适合 SEO 和数据获取
Client Component需要交互时使用 "use client"
generateStaticParams静态预渲染
generateMetadata动态 SEO 元信息
Server Action服务端函数,无需 API Route
revalidate增量静态再生

实践中的坑

  • Server Component 不能用 hooks:这个很容易忘,开发时要注意
  • import 顺序问题:如果一个 Client Component 导入了 Server Component,要确保 Server Component 先加载
  • API Key 泄露:敏感信息不要放在 NEXT_PUBLIC_ 前缀的变量中
  • ISR 缓存问题:如果页面没有更新,可能是缓存没失效,可以手动触发重新构建
  • CSS 冲突:使用 CSS Modules 或 Tailwind 可以避免大部分冲突