N Next.js 中文
原文 ↗

构建你的应用

了解运行 next build 时会发生什么,以及如何阅读构建输出。

更新于 2026-11-06Next.js 16.4.6

运行 next build 会为生产环境编译你的应用,预渲染符合条件的路由,并打印一张路由表,展示每个路由的提供方式。

next build 的作用

运行 next build 时,构建会经历以下几个阶段:

  1. 设置。 加载环境变量(.env 文件),验证你的next.config,并生成构建 ID。
  2. 路由发现。 扫描 app/ 和 pages/ 目录以查找路由,并检测根级约定文件,例如 proxy 和 instrumentation。生成 TypeScript 路由定义。
  3. 编译。 使用 Turbopack(或 webpack)打包客户端、服务器和边缘代码。转译 TypeScript 和 JSX,对未使用的代码进行 tree-shaking,并优化 CSS 和字体。
  4. 静态分析。 对每个路由进行分类,以区分预渲染和按需渲染。收集 generateStaticParams 输出。启用 Cache Components 时,检查阻止预渲染的错误。
  5. 预渲染。 将静态页面和 PPR 外壳预渲染为 HTML。为客户端导航生成 RSC 载荷。
  6. 输出。 将构建结果写入 .next/。对于 output: 'standalone',只打包运行时所需的文件。对于 output: 'export',生成完整的静态站点。打印路由表。

除非启用了 typescript.ignoreBuildErrors,否则构建会检查 TypeScript。

next dev 会将正在运行的开发服务器的状态和增量编译缓存存储在 .next/dev 中。删除或移动 .next 会丢弃该状态,因此开发服务器必须重新创建它。要运行隔离的生产构建,请配置单独的 distDir。

阅读构建输出

构建命令取决于你的包管理器:

pnpm

pnpm build

npm

npm run build

yarn

yarn build

bun

bun run build

构建成功后,Next.js 会打印一张路由表,每个路由旁边都有一个符号。

这些符号会有所不同,具体取决于是否启用了 Cache Components。

未启用 Cache Components

未启用 Cache Components 时,App Router 页面和 Pages Router 路由使用以下渲染分类:

符号 名称 行为
○ 静态 Next.js 将整个路由预渲染为 HTML。
● SSG Next.js 将来自 generateStaticParams 或 getStaticProps 的路径预渲染为 HTML。
ƒ 动态 Next.js 按需渲染该路由。

使用 Cache Components 时

使用 Cache Components 时,部分预渲染 是 App Router 页面唯一的渲染模型。对于这些页面,符号表示构建过程生成了多少 HTML:

符号 名称 行为
○ 静态 Next.js 将整个路由预渲染为 HTML。
◐ 部分预渲染 Next.js 预渲染静态 HTML 外壳,并按需渲染其余内容。
ƒ 动态 Next.js 按需渲染该路由。

对于 Cache Components 页面,ƒ 表示构建过程接受了空的 HTML 预渲染。Next.js 会在请求时渲染该路由。动态路由还可以包含针对 generateStaticParams 未返回的路径名的回退内容。

其他路由条目

依赖请求的路由处理器(API 端点)、Proxy(中间件)以及动态元数据路由(如 icon、opengraph-image 和 twitter-image)使用 ƒ。这些条目按需渲染,不使用 PPR。

预渲染校验

使用 Cache Components 时,next build 会校验每个 App Router 页面都能生成静态外壳。在 <Suspense> 之外使用 params、cookies() 和 headers() 等请求时值会产生运行时数据错误。未缓存的数据会产生未缓存数据错误。每个错误都会链接到适用于该数据源的修复方法。

调试预渲染错误

生产构建会压缩服务器代码,并默认省略服务器 source map。使用 --debug-prerender 可以获得更详细的堆栈跟踪和代码帧:

Terminalbash
next build --debug-prerender

该选项会禁用服务器端压缩、启用服务器 source map,并防止某个路由失败时中断构建的其余部分。

警告:

不要部署使用 --debug-prerender 生成的构建产物。这些构建包含调试选项,并未针对生产环境进行优化。

构建特定路由

在调试大型应用时,使用 --debug-build-paths 来编译并预渲染选定的路由。该选项接受逗号分隔的路径和 glob 模式。在模式前加上 ! 即可排除它。你也可以将其与 --debug-prerender 组合使用。

只有匹配的路由会出现在路由表中。当你选择一个 App Router 路由时,Next.js 还会包含内置的 /_not-found 路由。

示例

须知:

以下示例使用 Cache Components 与 Partial Prefetching,并在 next.config.ts 中通过 cacheComponents: true 和 partialPrefetching: true 启用。禁用 Cache Components 时,路由符号和预渲染错误会有所不同。有关设置方法,请参阅启用 Cache Components。

找出阻塞的工作

在此示例中,一个商店应用有一个产品页面,其中包含动态的 [id] 段:

app/
├── layout.tsx
├── page.tsx
└── products/
    └── [id]/
        └── page.tsx

页面读取 id 参数以获取产品:

TypeScript

app/products/[id]/page.tsxtsx
export default async function Page(props: PageProps<'/products/[id]'>) {
  const { id } = await props.params
  const res = await fetch(`https://api.example.com/products/${id}`)
  const product = await res.json()
  return <div>{product.name}</div>
}

JavaScript

app/products/[id]/page.jsjsx
export default async function Page({ params }) {
  const { id } = await params
  const res = await fetch(`https://api.example.com/products/${id}`)
  const product = await res.json()
  return <div>{product.name}</div>
}

运行 next build。Next.js 会尽可能多地预渲染每个路由,然后打印构建输出。在本例中,构建失败:

Terminalbash
Error: Route "/products/[id]": Next.js encountered uncached or runtime data during prerendering.

`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.

Ways to fix this:
  - [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
  - [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
  - [block] Set `export const instant = false` to allow a blocking route

Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
    at body (<anonymous>)
    at html (<anonymous>)
To get a more detailed stack trace and pinpoint the issue, try one of the following:
  - Start the app in development mode by running `next dev`, then open "/products/[id]" in your browser to investigate the error.
  - Rerun the production build with `next build --debug-prerender` to generate better stack traces.
Error occurred prerendering page "/products/[id]".

错误表明请求时的工作正在阻塞预渲染,但堆栈只指向 body 和 html。它没有指出源代码行。将两个调试选项结合使用,可以为产品路由生成详细的堆栈跟踪:

Terminalbash
next build --debug-prerender --debug-build-paths="app/products/[id]/page.tsx"

现在堆栈指向页面中第一个被阻塞的访问,即 params 读取:

Terminalbash
Error: Route "/products/[id]": Next.js encountered uncached or runtime data during prerendering.
  ...
    at Page (app/products/[id]/page.tsx:2:30)
  1 | export default async function Page(props: PageProps<'/products/[id]'>) {
> 2 |   const { id } = await props.params
    |                              ^
  3 |   const res = await fetch(`https://api.example.com/products/${id}`)
  4 |   const product = await res.json()

详细的堆栈将 params 读取识别为第一个被阻塞的访问。

在开发过程中,next dev 会在开发浮层和终端中显示所有验证错误,并提供可解析到源代码的堆栈帧。你编辑时它会重新运行验证。有关此开发工作流,请参阅确保即时导航。

本指南其余部分使用生产构建,以便你比较每项更改对路由表的影响。

该错误会根据请求时的工作能否流式渲染、能否缓存,还是必须阻塞路由,提供三种选项。第一种方式是流式渲染回退 UI。

流式渲染的产品页面

当路由有可在请求时数据加载期间展示的有用 UI 时,请选择该错误的 [stream] 选项。Next.js 会预渲染该回退内容,然后在参数和产品数据解析完成后将其替换为产品页面。在此路由中,loading.js 文件提供回退内容:

TypeScript

app/products/[id]/loading.tsxtsx
export default function Loading() {
  return <div>Loading...</div>
}

JavaScript

app/products/[id]/loading.jsjsx
export default function Loading() {
  return <div>Loading...</div>
}

loading.js 将页面包裹在 <Suspense> 边界中,并使用 loading 组件作为其回退内容。Next.js 将该回退内容预渲染为产品路由的静态外壳。页面在请求时读取参数并获取产品数据,然后用完整内容替换回退内容。

如需更细粒度的流式渲染,可仅在需要请求时数据的组件周围添加显式的 <Suspense> 边界。这样页面的更多部分就可以保留在静态外壳中。请参阅 流式渲染。

构建应用:

Terminalbash
next build

构建通过:

Terminalbash
Route (app)
┌ ○ /
├ ○ /_not-found
└ ◐ /products/[id]

○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content

◐ 符号表示该路由提供静态外壳并流式渲染其余内容。

预渲染的产品页面

该路由现在拥有来自 loading.js 的段级回退内容。要为已知产品预渲染页面,请保留 loading.js 并使用 generateStaticParams 提供它们的 ID:

TypeScript

app/products/[id]/page.tsxtsx
export async function generateStaticParams() {
  const res = await fetch('https://api.example.com/products')
  const products = await res.json()
  return products.map((product) => ({ id: product.id }))
}

export default async function Page(props: PageProps<'/products/[id]'>) {
  const { id } = await props.params
  const res = await fetch(`https://api.example.com/products/${id}`)
  const product = await res.json()
  return <div>{product.name}</div>
}

JavaScript

app/products/[id]/page.jsjsx
export async function generateStaticParams() {
  const res = await fetch('https://api.example.com/products')
  const products = await res.json()
  return products.map((product) => ({ id: product.id }))
}

export default async function Page({ params }) {
  const { id } = await params
  const res = await fetch(`https://api.example.com/products/${id}`)
  const product = await res.json()
  return <div>{product.name}</div>
}

重新构建应用:

Terminalbash
next build

现在 Next.js 会尝试为每个产品 ID 预渲染一个页面:

Terminalbash
Route (app)
┌ ○ /
├ ○ /_not-found
└   /products/[id]      # Route pattern group
  ├ ◐ /products/[id]    # Fallback row
  ├ ◐ /products/1       # Product content streams into the static shell
  ├ ◐ /products/2
  └ ◐ /products/3

○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content

未标记的 /products/[id] 行将其下的路由输出分组。每个缩进的行保持 ◐。loading.js 回退内容会被预渲染,随后产品在请求时加载并流式渲染到该外壳中。

须知:

generateStaticParams 是可选的。当一组路径名在构建时已知且值得预渲染时,请使用它。使用 Cache Components 时,它必须返回至少一个 param。空数组会导致构建错误。

缓存的产品数据

当产品查询可以在多个请求之间复用,而不是为每位访客运行时,请选择该错误的 [cache] 选项。缓存让 Next.js 在预渲染已知产品时包含产品数据,从而为这些路径生成完整的 HTML。在查询中添加 use cache:

TypeScript

app/products/[id]/page.tsxtsx
export async function generateStaticParams() {
  const res = await fetch('https://api.example.com/products')
  const products = await res.json()
  return products.map((product) => ({ id: product.id }))
}

async function getProduct(id: string) {
  'use cache'
  const res = await fetch(`https://api.example.com/products/${id}`)
  return res.json()
}

export default async function Page(props: PageProps<'/products/[id]'>) {
  const { id } = await props.params
  const product = await getProduct(id)
  return <div>{product.name}</div>
}

JavaScript

app/products/[id]/page.jsjsx
export async function generateStaticParams() {
  const res = await fetch('https://api.example.com/products')
  const products = await res.json()
  return products.map((product) => ({ id: product.id }))
}

async function getProduct(id) {
  'use cache'
  const res = await fetch(`https://api.example.com/products/${id}`)
  return res.json()
}

export default async function Page({ params }) {
  const { id } = await params
  const product = await getProduct(id)
  return <div>{product.name}</div>
}

重新构建应用后,列出的参数会显示为 ○。它们的参数已知且数据已缓存,因此 Next.js 会完整预渲染每个页面。回退行仍为 ◐:

Terminalbash
Route (app)
┌ ○ /
├ ○ /_not-found
└   /products/[id]      # Route pattern group
  ├ ◐ /products/[id]    # Fallback row
  ├ ○ /products/1       # Full HTML prerender
  ├ ○ /products/2
  └ ○ /products/3

○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content

/products/[id] 回退内容代表 generateStaticParams 未返回的产品 ID。它保持为 ◐,因为构建时无法知道所有产品 ID。首次访问未列出的产品时,部分预取会立即提供 loading.js 回退内容,同时 Next.js 为该 ID 渲染页面并将其存储到 ISR 缓存中。后续访问将收到完整页面,而不是回退内容。完整的升级流程请参阅 使用 Cache Components 的 ISR。

当预渲染的路径多到无法全部显示在表格中时,Next.js 会打印一个简短列表,并以 [+N more paths] 结尾。

包含缓存函数或组件的路由还可以显示 Revalidate 和 Expire 列。路由会报告其包含的所有缓存中最短的 revalidate 和 expire。当没有显式的 cacheLife 调用时,缓存使用 default 配置。渲染相同缓存数据的 /products 列表页会产生以下输出:

Terminalbash
Route (app)           Revalidate  Expire
┌ ○ /
├ ○ /_not-found
├ ○ /products                15m      1y
└   /products/[id]
  ├ ◐ /products/[id]
  ├ ○ /products/1            15m      1y
  ├ ○ /products/2            15m      1y
  └ ○ /products/3            15m      1y

默认的 use cache 配置 会在 15 分钟后重新验证。该路由的默认 expireTime 为一年,因此表格显示 15m 和 1y。你可以在 next.config.ts 中配置这两个值。

一个阻塞式的产品页面

当等待请求时工作才是该路由的正确行为时,请选择该错误中的 [block] 选项。该路由可能需要在响应前获得完整结果,或者你可能希望在逐步采用 Cache Components 的同时推迟一项困难的重构。

假设这个产品路由暂时需要保持阻塞。保留 generateStaticParams,删除 loading 文件和 use cache 指令,然后设置 instant = false:

TypeScript

app/products/[id]/page.tsxtsx
import { notFound } from 'next/navigation'

export const instant = false

export async function generateStaticParams() {
  const res = await fetch('https://api.example.com/products')
  const products = await res.json()
  return products.map((product) => ({ id: product.id }))
}

export default async function Page(props: PageProps<'/products/[id]'>) {
  const { id } = await props.params
  const res = await fetch(`https://api.example.com/products/${id}`)
  if (!res.ok) {
    notFound()
  }
  const product = await res.json()
  return <div>{product.name}</div>
}

JavaScript

app/products/[id]/page.jsjsx
import { notFound } from 'next/navigation'

export const instant = false

export async function generateStaticParams() {
  const res = await fetch('https://api.example.com/products')
  const products = await res.json()
  return products.map((product) => ({ id: product.id }))
}

export default async function Page({ params }) {
  const { id } = await params
  const res = await fetch(`https://api.example.com/products/${id}`)
  if (!res.ok) {
    notFound()
  }
  const product = await res.json()
  return <div>{product.name}</div>
}

移除 loading 边界后,页面在等待 params 和产品查找期间无法渲染任何回退内容。移除 use cache 意味着每次请求也会运行该查找。在客户端导航期间,当前页面会保持可见,直到产品页面或 not-found UI 准备就绪。

instant = false 会为此路由禁用即时导航验证,包括非空静态 shell 检查。这使导航可以等待产品页面或 not-found UI,同时该路由仍可预渲染。

构建输出现在显示:

Terminalbash
Route (app)
┌ ○ /
├ ○ /_not-found
└   /products/[id]      # Route pattern group
  ├ ƒ /products/[id]    # Empty fallback for unlisted IDs
  ├ ƒ /products/1       # Rendered on request with no HTML prerender
  ├ ƒ /products/2
  └ ƒ /products/3

○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand

缩进的 /products/[id] 行是 generateStaticParams 未返回的 ID 的回退项。其他缩进行是生成的产品路径。产品查找会在生成的路径产出 HTML 之前阻塞它们,而 params 会先阻塞回退项。每次预渲染都是空的,并使用 ƒ。当共享布局将 children 包裹在 <Suspense> 中时,Next.js 会将其回退内容保留为静态 shell,并改用 ◐。

诸如 Math.random()、new Date() 和 crypto.randomUUID() 之类的同步值仍会产生预渲染错误。

后续步骤

进一步了解部署、缓存和配置生产构建。

  • 部署:了解如何部署你的 Next.js 应用。
  • 缓存:了解如何在 Next.js 中缓存数据和 UI
  • 使用 Cache Components 的 ISR:了解如何预渲染一部分动态路由,为其余路由提供 App Shell,并在首次访问后升级它们。
  • CI 构建缓存:了解如何配置 CI 来缓存 Next.js 构建