构建你的应用程序
了解运行 next build 时会发生什么,以及如何阅读构建输出。
运行 next build 会为生产环境编译你的应用程序,预渲染符合条件的路由,并打印一个路由表,显示每个路由的服务方式。
next build 做了什么#
当你运行 next build 时,构建会经历以下阶段:
- 设置。 加载环境变量(
.env文件),校验你的next.config,并生成一个构建 ID。 - 路由发现。 扫描
app/和pages/目录以查找路由,并检测根级别的约定文件,如proxy和instrumentation。生成 TypeScript 路由定义。 - 编译。 使用 Turbopack(或 webpack)打包客户端、服务端和边缘(edge)代码。转译 TypeScript 和 JSX,摇树优化(tree-shake)未使用的代码,并优化 CSS 和字体。
- 静态分析。 将每个路由分类为预渲染或按需渲染。收集
generateStaticParams的输出。使用 Cache Components 时,检查是否存在阻塞预渲染的错误。 - 预渲染。 将静态页面和 PPR 外壳(shell)预渲染为 HTML。为客户端导航生成 RSC Payload。
- 输出。 将构建产物写入
.next/。对于output: 'standalone',仅打包运行时所需的文件。对于output: 'export',生成完整的静态站点。打印路由表。
除非启用了 typescript.ignoreBuildErrors,否则构建会检查 TypeScript。
next dev 会将正在运行的开发服务器的状态和增量编译缓存存储在 .next/dev 中。删除或移动 .next 会丢弃这些状态,因此开发服务器必须重新创建它们。要运行一个隔离的生产构建,请配置单独的 distDir。
阅读构建输出#
构建命令取决于你使用的包管理器:
pnpm buildnpm run buildyarn buildbun run build构建成功后,Next.js 会打印一个路由表,每个路由旁边都有一个符号。
这些符号会因是否启用 Cache Components 而有所不同。
未启用 Cache Components 时#
未启用 Cache Components 时,App Router 页面和 Pages Router 路由使用以下渲染分类:
| 符号 | 名称 | 行为 |
|---|---|---|
○ | 静态(Static) | Next.js 将整个路由预渲染为 HTML。 |
● | SSG | Next.js 将 generateStaticParams 或 getStaticProps 生成的路径预渲染为 HTML。 |
ƒ | 动态(Dynamic) | Next.js 按需渲染该路由。 |
启用 Cache Components 时#
使用 Cache Components 时,Partial Prerendering 是 App Router 页面唯一的渲染模型。对于这些页面,符号描述了构建生成了多少 HTML:
| 符号 | 名称 | 行为 |
|---|---|---|
○ | 静态(Static) | Next.js 将整个路由预渲染为 HTML。 |
◐ | 部分预渲染(Partial Prerender) | Next.js 预渲染一个静态 HTML 外壳(shell),并按需渲染其余内容。 |
ƒ | 动态(Dynamic) | Next.js 按需渲染该路由。 |
对于 Cache Components 页面,ƒ 表示构建接受了一个空的 HTML 预渲染。Next.js 在请求时渲染该路由。动态路由还可以包含针对 generateStaticParams 未返回的路径名的回退(fallback)。
其他路由条目#
依赖请求的 Route Handler(API 端点)、Proxy(Middleware)以及动态元数据路由(如 icon、opengraph-image 和 twitter-image)使用 ƒ。这些条目按需渲染,不使用 PPR。
预渲染校验#
使用 Cache Components 时,next build 会校验每个 App Router 页面是否能生成静态外壳(shell)。<Suspense> 之外的 params、cookies() 和 headers() 等请求时值会产生运行时数据错误。未缓存的数据会产生未缓存数据错误。每个错误都会链接到适用于该数据源的修复方法。
调试预渲染错误#
生产构建默认会压缩服务端代码并省略服务端 source map。使用 --debug-prerender 可以获得更详细的堆栈跟踪和代码帧:
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 参数来获取商品:
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>
}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 会在打印构建输出之前尽可能多地预渲染每个路由。在本例中,构建失败了:
Error: 路由 "/products/[id]":Next.js 在预渲染期间遇到了未缓存的数据或运行时数据。
在 `<Suspense>` 之外访问 `fetch(...)`、`cookies()`、`headers()`、`params`、`searchParams` 或 `connection()` 会阻止路由被预渲染,从而阻塞页面加载并导致更慢的用户体验。
修复方法:
- [stream] 使用 `<Suspense fallback={...}>` 在数据访问周围提供一个占位符
- [cache] 对于未缓存的数据(`fetch`、数据库调用):使用 `"use cache"` 缓存该访问(不适用于 `connection()`)
- [block] 设置 `export const instant = false` 以允许阻塞路由
了解更多:https://nextjs.org/docs/messages/blocking-prerender-dynamic
at body (<anonymous>)
at html (<anonymous>)
要获取更详细的堆栈跟踪并定位问题,请尝试以下方法之一:
- 通过运行 `next dev` 以开发模式启动应用,然后在浏览器中打开 "/products/[id]" 来调查错误。
- 使用 `next build --debug-prerender` 重新运行生产构建以生成更好的堆栈跟踪。
预渲染页面 "/products/[id]" 时出错。该错误表明请求时的工作正在阻塞预渲染,但堆栈只指向 body 和 html,并未指出源代码行。结合使用这两个调试选项可以生成该商品路由的详细堆栈跟踪:
next build --debug-prerender --debug-build-paths="app/products/[id]/page.tsx"现在堆栈指向页面中第一个被阻塞的访问,即对 params 的读取:
Error: 路由 "/products/[id]":Next.js 在预渲染期间遇到了未缓存的数据或运行时数据。
...
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 会在开发遮罩层(dev overlay)和终端中显示所有校验错误,并提供解析到你的源代码的堆栈帧。它会在你编辑时重新运行校验。有关开发工作流,请参阅确保即时导航。
本指南的其余部分使用生产构建,以便你比较每项更改如何影响路由表。
该错误根据请求时的工作是可以流式传输、可以缓存还是必须阻塞路由,提供了三个选项。第一种方法会流式传输回退 UI。
流式传输的商品页面#
当路由在请求时数据加载期间有有用的 UI 可显示时,选择错误提示中的 [stream] 选项。Next.js 会预渲染该回退内容,然后在 params 和商品数据解析后将其替换为商品页面。在这个路由中,loading.js 文件提供了回退内容:
export default function Loading() {
return <div>Loading...</div>
}export default function Loading() {
return <div>Loading...</div>
}loading.js 将页面包裹在一个 <Suspense> 边界中,并使用 loading 组件作为其回退内容。Next.js 将此回退内容预渲染为商品路由的静态外壳(shell)。页面在请求时读取 params 并获取商品,然后用完成的内容替换回退内容。
要进行更细粒度的流式传输,可以仅在需要请求时数据的组件周围添加显式的 <Suspense> 边界。这样页面的更多部分可以保留在静态外壳中。请参阅流式传输。
构建应用程序:
next build构建通过了:
Route (app)
┌ ○ /
├ ○ /_not-found
└ ◐ /products/[id]
○ (Static) 预渲染为静态内容
◐ (Partial Prerender) 预渲染为静态 HTML,并包含服务端流式传输的动态内容◐ 符号表示该路由提供静态外壳(shell),并流式传输其余内容。
预渲染的商品页面#
现在该路由通过 loading.js 拥有了段级别的回退内容。要为已知商品预渲染页面,请保留 loading.js 并使用 generateStaticParams 提供它们的 ID:
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/products')
const products = await res.json()
return products.slice(0, 12).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>
}export async function generateStaticParams() {
const res = await fetch('https://api.example.com/products')
const products = await res.json()
return products.slice(0, 12).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>
}重新构建应用程序:
next buildNext.js 现在会尝试为每个商品 ID 预渲染一个页面:
Route (app)
┌ ○ /
├ ○ /_not-found
└ /products/[id] # 路由模式分组
├ ◐ /products/[id] # 回退行
├ ◐ /products/1 # 商品内容流式进入静态外壳
├ ◐ /products/2
└ ◐ [+10 more paths]
○ (Static) 预渲染为静态内容
◐ (Partial Prerender) 预渲染为静态 HTML,并包含服务端流式传输的动态内容未加标记的 /products/[id] 行将其下方的路由输出分组。当预渲染的路径数量超出表格可容纳的范围时,Next.js 会打印一个简短列表,并以 [+N more paths] 结尾。每个缩进行都保持为 ◐。loading.js 的回退内容会被预渲染,然后商品在请求时加载并流式进入该外壳。
小知识:
generateStaticParams是可选的。当一组路径名在构建时已知且值得预渲染时使用它。使用 Cache Components 时,它必须返回至少一个参数。返回空数组会导致构建错误。
缓存的商品数据#
当商品查询可以跨请求复用而不是为每位访问者都运行时,选择错误提示中的 [cache] 选项。缓存使 Next.js 在预渲染已知商品时能够包含商品数据,从而为这些路径生成完整的 HTML。在查询函数中添加 use cache:
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/products')
const products = await res.json()
return products.slice(0, 12).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>
}export async function generateStaticParams() {
const res = await fetch('https://api.example.com/products')
const products = await res.json()
return products.slice(0, 12).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 会完整预渲染每个页面。回退行仍为 ◐:
Route (app)
┌ ○ /
├ ○ /_not-found
└ /products/[id] # 路由模式分组
├ ◐ /products/[id] # 回退行
├ ○ /products/1 # 完整 HTML 预渲染
├ ○ /products/2
└ ○ [+10 more paths]
○ (Static) 预渲染为静态内容
◐ (Partial Prerender) 预渲染为静态 HTML,并包含服务端流式传输的动态内容/products/[id] 回退表示 generateStaticParams 未返回的商品 ID。它保持为 ◐,因为构建并不知道所有商品 ID。首次访问未列出的商品时,Partial Prefetching 会立即提供 loading.js 回退内容,同时 Next.js 为该 ID 渲染页面并将其存储在 ISR 缓存中。后续访问将收到完成的页面而不是回退内容。有关完整的升级流程,请参阅使用 Cache Components 的 ISR。
包含缓存函数或组件的路由还会显示 Revalidate 和 Expire 列。路由会报告其包含的所有缓存中最短的 revalidate 和 expire 值。当没有显式调用 cacheLife 时,缓存使用 default 配置文件。渲染相同缓存数据的 /products 列表页会产生如下输出:
Route (app) Revalidate Expire
┌ ○ /
├ ○ /_not-found
├ ○ /products 15m 1y
└ /products/[id]
├ ◐ /products/[id]
├ ○ /products/1 15m 1y
├ ○ /products/2 15m 1y
└ ○ [+10 more paths]默认的 use cache 配置文件会在 15 分钟后重新验证。路由的默认 expireTime 为一年,因此表中显示 15m 和 1y。你可以在 next.config.ts 中配置这两个值。
阻塞式商品页面#
当等待请求时的工作是该路由的正确行为时,选择错误提示中的 [block] 选项。路由可能需要在响应之前获得完整结果,或者你可能希望在逐步采用 Cache Components 的同时推迟困难的重构。
假设这个商品路由目前需要保持阻塞。保留 generateStaticParams,移除 loading 文件和 use cache 指令,然后设置 instant = false:
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.slice(0, 12).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>
}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.slice(0, 12).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 会禁用该路由的即时导航校验,包括非空静态外壳检查。这让导航可以等待商品页面或 not-found UI,同时该路由仍然可以预渲染。
现在的构建输出显示:
Route (app)
┌ ○ /
├ ○ /_not-found
└ /products/[id] # 路由模式分组
├ ƒ /products/[id] # 用于未列出 ID 的空回退
├ ƒ /products/1 # 按需渲染,不进行 HTML 预渲染
├ ƒ /products/2
└ ƒ [+10 more paths]
○ (Static) 预渲染为静态内容
ƒ (Dynamic) 按需进行服务端渲染缩进的 /products/[id] 行是 generateStaticParams 未返回 ID 的回退。其他缩进行是生成的商品路径。商品查询会在生成的路径产生 HTML 之前阻塞它们,而 params 首先阻塞回退。每次预渲染都是空的并使用 ƒ。当共享布局将 children 包裹在 <Suspense> 中时,Next.js 会保留其回退内容作为静态外壳,并改用 ◐。
诸如 Math.random()、new Date() 和 crypto.randomUUID() 之类的同步值仍然会产生预渲染错误。