NNext.js 中文网 GitHub

如何升级到版本 16

将 Next.js 应用从版本 15 升级到 16。

使用编码智能体(推荐)#

在应用目录中运行最新的升级 CLI:

Terminal
npx next@canary upgrade --agent=latest

CLI 会为智能体准备 Next.js 16 迁移指南和 codemod 命令,然后让它应用更改并验证应用。有关详情,请参阅使用编码智能体升级。

或手动升级#

手动升级需要按顺序执行以下几个步骤:

  1. 如果你现在使用编码智能体,或希望将来的智能体工作基于与版本匹配的文档,请设置 AI 智能体文档。
  2. 运行升级 codemod。
  3. 如果你不想运行 codemod,请手动安装包。
  4. 继续阅读下方的破坏性变更,运行相关检查,并修复任何剩余问题。

设置 AI 智能体文档#

升级之前,将 AGENTS.md 指向与版本匹配的 Next.js 文档,以便编码智能体协助完成后续步骤:

Terminal
npx @next/codemod@canary agents-md

升级后,检查 AGENTS.md 是否指向 node_modules/next/dist/docs/ 中与所安装版本捆绑的文档。运行 next dev 会使此代码块保持最新。如果安装过程将文档下载到 .next-docs/,请在没有任何引用后删除该目录。有关托管代码块和设置详情,请参阅与版本匹配的文档。

使用 codemod#

要更新到 Next.js 版本 16,可以使用 upgrade codemod:

bash · pnpm
pnpm dlx @next/codemod@canary upgrade latest
bash · npm
npx @next/codemod@canary upgrade latest
bash · yarn
yarn dlx @next/codemod@canary upgrade latest
bash · bun
bunx @next/codemod@canary upgrade latest

codemod 能够:

  • 更新 next.config.js 以使用新的 turbopack 配置
  • 从 next lint 迁移到 ESLint CLI
  • 从已弃用的 middleware 约定迁移到 proxy
  • 从已稳定的 API 中移除 unstable_ 前缀
  • 从页面和布局中移除 experimental_ppr Route Segment Config

upgrade codemod 不会运行所有迁移 codemod。如果你的应用仍使用 Next.js 15 兼容期的同步 params、searchParams、cookies()、headers() 或 draftMode() 访问,还需运行异步 Request APIs codemod:

Terminal
npx @next/codemod@canary next-async-request-api .

手动安装包#

如果你更喜欢手动操作,请安装最新的 Next.js 和 React 版本:

bash · pnpm
pnpm add next@latest react@latest react-dom@latest
bash · npm
npm install next@latest react@latest react-dom@latest
bash · yarn
yarn add next@latest react@latest react-dom@latest
bash · bun
bun add next@latest react@latest react-dom@latest

如果使用 TypeScript,请确保也将 @types/react 和 @types/react-dom 升级到最新版本。

Node.js 运行时和浏览器支持#

要求变更 / 详情
Node.js 20.9+最低版本现为 20.9.0(LTS);不再支持 Node.js 18
TypeScript 5+最低版本现为 5.1.0
浏览器Chrome 111+、Edge 111+、Firefox 111+、Safari 16.4+

默认使用 Turbopack#

从 Next.js 16 开始,Turbopack 已稳定,并默认用于 next dev 和 next build

以前必须使用 --turbopack 或 --turbo 来启用 Turbopack。

package.json
{
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build --turbopack",
    "start": "next start"
  }
}

现在不再需要这样做。你可以更新 package.json 脚本:

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

如果你的项目有自定义 webpack 配置,并且运行 next build(现在默认使用 Turbopack),构建将失败,以防止配置错误问题。

你可以通过几种不同的方式解决此问题:

  • 仍然使用 Turbopack:使用 next build --turbopack 运行,以使用 Turbopack 构建并忽略 webpack 配置。
  • 完全切换到 Turbopack:将 webpack 配置迁移到与 Turbopack 兼容的选项。
  • 继续使用 Webpack:使用 --webpack 标志选择退出 Turbopack,并使用 Webpack 构建。

小知识:如果看到因发现 webpack 配置而导致的构建失败,但你自己并未定义该配置,那么很可能是某个插件添加了 webpack 选项

选择退出 Turbopack#

如果需要继续使用 Webpack,可以使用 --webpack 标志选择退出。例如,在开发中使用 Turbopack,而在生产构建中使用 Webpack:

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build --webpack",
    "start": "next start"
  }
}

我们建议在开发和生产环境中都使用 Turbopack。如果无法切换到 Turbopack,请在此讨论帖中发表评论。

Turbopack 配置位置#

experimental.turbopack 配置已脱离实验阶段。

next.config.ts
import type { NextConfig } from 'next'

// Next.js 15 - experimental.turbopack
const nextConfig: NextConfig = {
  experimental: {
    turbopack: {
      // 选项
    },
  },
}

export default nextConfig

可以将其用作顶层 turbopack 选项:

next.config.ts
import type { NextConfig } from 'next'

// Next.js 16 - nextConfig 顶层的 turbopack
const nextConfig: NextConfig = {
  turbopack: {
    // 选项
  },
}

export default nextConfig

请务必查看 Turbopack 配置选项。Next.js 16 引入了多项改进和新选项,例如:

解析别名回退#

在某些项目中,客户端代码可能会导入包含 Node.js 原生模块的文件。这会导致 Module not found: Can't resolve 'fs' 这类错误。

发生这种情况时,应重构代码,使客户端包不引用这些 Node.js 原生模块。

不过,在某些情况下这可能不可行。在 Webpack 中,通常使用 resolve.fallback 选项来消除该错误。Turbopack 提供了类似的选项 turbopack.resolveAlias。在这种情况下,告诉 Turbopack 在浏览器请求 fs 时加载一个空模块。

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  turbopack: {
    resolveAlias: {
      fs: {
        browser: './empty.ts', // 建议在使用此方法之前修复代码导入
      },
    },
  },
}

export default nextConfig

更好的做法是重构模块,使客户端代码永远不会从使用 Node.js 原生模块的模块中导入。

从 node_modules 导入 Sass#

Turbopack 完全支持从 node_modules 导入 Sass 文件。请注意,虽然 Webpack 允许使用旧式的波浪号(~)前缀,但 Turbopack 不支持这种语法。

在 Webpack 中:

styles/globals.scss
@import '~bootstrap/dist/css/bootstrap.min.css';

在 Turbopack 中:

styles/globals.scss
@import 'bootstrap/dist/css/bootstrap.min.css';

如果无法更改导入方式,可以使用 turbopack.resolveAlias。例如:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  turbopack: {
    resolveAlias: {
      '~*': '*',
    },
  },
}

export default nextConfig

Turbopack 文件系统缓存#

Turbopack 在两次运行之间将编译产物存储在磁盘上,从而在重启时显著加快编译速度。next dev 和 next build 都通过 experimental.turbopackFileSystemCacheForDev 和 experimental.turbopackFileSystemCacheForBuild 默认启用文件系统缓存。请参阅 Turbopack 文件系统缓存以配置或禁用其中任一项。

异步 Request APIs(破坏性变更)#

版本 15 引入了 Async Request APIs 作为破坏性变更,并带有临时的同步兼容性。

从 Next.js 16 开始,同步访问被完全移除。这些 API 只能通过异步方式访问。

使用 codemod 迁移到异步请求时 API。

迁移异步请求时 API 的类型#

为了帮助迁移到异步 params 和 searchParams,可以运行 npx next typegen 自动生成这些全局可用的类型辅助工具:

小知识:typegen 是在 Next.js 15.5 中引入的

这简化了向新异步 API 模式的类型安全迁移,并使你能够以完整的类型安全性更新组件,例如:

/app/blog/[slug]/page.tsx
export default async function Page(props: PageProps<'/blog/[slug]'>) {
  const { slug } = await props.params
  const query = await props.searchParams
  return <h1>Blog Post: {slug}</h1>
}

这种方式让你可以在页面中直接以完全类型安全的方式访问 props.params(包括 slug)和 searchParams。

icon 和 open-graph Image 的异步参数(破坏性变更)#

传递给 opengraph-image、twitter-image、icon 和 apple-icon 中图像生成函数的 props 现在是 Promise。

在以前的版本中,Image(图像生成函数)和 generateImageMetadata 都会接收一个 params 对象。generateImageMetadata 返回的 id 会作为字符串传递给图像生成函数。

app/shop/[slug]/opengraph-image.js
// Next.js 15 - 同步 params 访问
export function generateImageMetadata({ params }) {
  const { slug } = params
  return [{ id: '1' }, { id: '2' }]
}

// Next.js 15 - 同步 params 和 id 访问
export default function Image({ params, id }) {
  const slug = params.slug
  const imageId = id // string
  // ...
}

从 Next.js 16 开始,为与 Async Request APIs 变更保持一致,图像生成函数现在以 Promise 形式接收 params 和 id。generateImageMetadata 函数仍接收同步的 params。

app/shop/[slug]/opengraph-image.js
export async function generateImageMetadata({ params }) {
  const { slug } = params
  return [{ id: '1' }, { id: '2' }]
}

// Next.js 16 - 异步 params 和 id 访问
export default async function Image({ params, id }) {
  const { slug } = await params // params 现在是异步的
  const imageId = await id // 使用 generateImageMetadata 时,id 现在是 Promise<string>
  // ...
}

sitemap 的异步 id 参数(破坏性变更)#

以前,generateSitemaps 返回的 id 值会直接传递给 sitemap 生成函数。

app/product/sitemap.js
export async function generateSitemaps() {
  return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}

// Next.js 15 - 同步 id 访问
export default async function sitemap({ id }) {
  const start = id * 50000 // id 是数字
  // ...
}

从 Next.js 16 开始,sitemap 生成函数现在以 Promise 形式接收 id。

app/product/sitemap.js
export async function generateSitemaps() {
  return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}

// Next.js 16 - 异步 id 访问
export default async function sitemap({ id }) {
  const resolvedId = await id // id 现在是 Promise<string>
  const start = Number(resolvedId) * 50000
  // ...
}

React 19.2#

Next.js 16 中的 App Router 使用最新的 React Canary 版本,其中包含新发布的 React 19.2 功能以及其他逐步稳定的功能。亮点包括:

  • View Transitions:为在 Transition 或导航中更新的元素添加动画
  • useEffectEvent:将非响应式逻辑从 Effect 中提取到可复用的 Effect Event 函数中
  • Activity:通过用 display: none 隐藏 UI 来渲染"后台活动",同时保持状态并清理 Effect

在 React 19.2 公告中了解更多信息。

React Compiler 支持#

随着 React Compiler 1.0 的发布,对 React Compiler 的内置支持现已在 Next.js 16 中稳定。React Compiler 会自动对组件进行记忆化,在无需手动更改代码的情况下减少不必要的重新渲染。

reactCompiler 配置项已从 experimental 提升为稳定。由于我们仍在收集不同应用类型的构建性能数据,它默认未启用。

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  reactCompiler: true,
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactCompiler: true,
}

module.exports = nextConfig

安装最新版本的 React Compiler 插件:

bash · pnpm
pnpm add -D babel-plugin-react-compiler
bash · npm
npm install -D babel-plugin-react-compiler
bash · yarn
yarn add -D babel-plugin-react-compiler
bash · bun
bun add -D babel-plugin-react-compiler

小知识:启用此选项时,由于 React Compiler 依赖 Babel,开发和构建时的编译时间可能会更长。

缓存 API#

revalidateTag#

revalidateTag 现在需要第二个参数来指定 cacheLife profile。单参数形式已弃用,会产生 TypeScript 错误。

ts
// 之前
revalidateTag('posts')

// 之后
revalidateTag('posts', 'max')

如果需要立即过期而不是 stale-while-revalidate,请在 Server Actions 中使用 updateTag。这还会保留客户端刷新。

app/actions.ts
'use server'

import { revalidateTag } from 'next/cache'

export async function updateArticle(articleId: string) {
  // 将文章数据标记为陈旧 - 读者在重新验证期间会看到旧数据
  revalidateTag(`article-${articleId}`, 'max')
}
app/actions.js
'use server'

import { revalidateTag } from 'next/cache'

export async function updateArticle(articleId) {
  // 将文章数据标记为陈旧 - 读者在重新验证期间会看到旧数据
  revalidateTag(`article-${articleId}`, 'max')
}

对于可以接受更新略有延迟的内容(例如博客文章、产品目录或文档),请使用 revalidateTag。用户会收到旧内容,而新数据在后台加载。

updateTag#

updateTag 是一个新的仅限 Server Actions 使用的 API,提供读己所写(read-your-writes)语义:用户做出更改后,UI 会立即显示该更改,而不是旧数据。

它通过在同一个请求中使数据过期并立即刷新来实现这一点。

app/actions.ts
'use server'

import { updateTag } from 'next/cache'

export async function updateUserProfile(userId: string, profile: Profile) {
  await db.users.update(userId, profile)

  // 使缓存过期并立即刷新 - 用户会立刻看到自己的更改
  updateTag(`user-${userId}`)
}
app/actions.js
'use server'

import { updateTag } from 'next/cache'

export async function updateUserProfile(userId, profile) {
  await db.users.update(userId, profile)

  // 使缓存过期并立即刷新 - 用户会立刻看到自己的更改
  updateTag(`user-${userId}`)
}

这确保交互功能能立即反映更改。非常适合表单、用户设置以及用户希望即时看到更新结果的任何工作流程。

在此处了解更多关于何时使用 updateTag 或 revalidateTag 的信息。

refresh#

refresh 允许你在 Server Action 中刷新客户端路由。

app/actions.ts
'use server'

import { refresh } from 'next/cache'

export async function markNotificationAsRead(notificationId: string) {
  // 更新数据库中的通知
  await db.notifications.markAsRead(notificationId)

  // 刷新头部显示的通知数量
  refresh()
}
app/actions.js
'use server'

import { refresh } from 'next/cache'

export async function markNotificationAsRead(notificationId) {
  // 更新数据库中的通知
  await db.notifications.markAsRead(notificationId)

  // 刷新头部显示的通知数量
  refresh()
}

当你需要在执行操作后刷新客户端路由时,请使用它。

cacheLife 和 cacheTag#

cacheLife 和 cacheTag 现已稳定。不再需要 unstable_ 前缀。

如果你之前使用如下别名导入:

ts
import {
  unstable_cacheLife as cacheLife,
  unstable_cacheTag as cacheTag,
} from 'next/cache'

可以将导入更新为:

ts
import { cacheLife, cacheTag } from 'next/cache'

增强的路由和导航#

Next.js 16 对路由和导航系统进行了全面重构,使页面过渡更轻量、更快速。这优化了 Next.js 预取和缓存导航数据的方式:

  • 布局去重:预取多个共享布局的 URL 时,该布局只下载一次。
  • 增量预取:Next.js 只预取尚未缓存的部分,而不是整个页面。

这些更改无需修改代码,旨在提升所有应用的性能。

不过,你可能会看到更多单独的预取请求,但总传输大小要小得多。我们认为这对几乎所有应用来说都是合适的权衡。

如果增加的请求数量导致问题,请通过创建 issue 或 discussion 告知我们。

部分预渲染(PPR)#

Next.js 16 移除了实验性的 Partial Prerendering(PPR) 标志和配置选项,包括路由级段配置 experimental_ppr。

从 Next.js 16 开始,可以使用 cacheComponents 配置选择启用 PPR。

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  cacheComponents: true,
}

module.exports = nextConfig

Next.js 16 中的 PPR 与 Next.js 15 canary 中的工作方式不同。如果你目前在使用 PPR,请继续留在当前使用的 Next.js 15 canary。有关迁移模式,请参阅迁移到 Cache Components。

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // 如果你目前在使用 PPR
  // 请继续留在当前的 Next.js 15 canary
  experimental: {
    ppr: true,
  },
}

module.exports = nextConfig

从 middleware 到 proxy#

middleware 文件名已弃用,并已重命名为 proxy,以明确网络边界和路由关注点。

proxy 中不支持 edge 运行时。proxy 的运行时是 nodejs,且无法配置。如果要继续使用 edge 运行时,请继续使用 middleware。我们将在后续次要版本中提供更多关于 edge 运行时的说明。

Terminal
# 重命名 middleware 文件
mv middleware.ts proxy.ts
# 或者
mv middleware.js proxy.js

命名导出 middleware 也已弃用。请将函数重命名为 proxy。

proxy.ts
export function proxy(request: Request) {}
proxy.js
export function proxy(request) {}

即使你使用的是默认导出,我们也建议将函数名改为 proxy。

包含 middleware 名称的配置标志也已重命名。例如,skipMiddlewareUrlNormalize 现在改为 skipProxyUrlNormalize

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  skipProxyUrlNormalize: true,
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  skipProxyUrlNormalize: true,
}

module.exports = nextConfig

版本 16 的 codemod 也能更新这些标志。

next/image 变更#

带查询字符串的本地图片(破坏性变更)#

带查询字符串的本地图片来源现在需要 images.localPatterns.search 配置,以防止枚举攻击。

app/page.tsx
import Image from 'next/image'

export default function Page() {
  return <Image src="/assets/photo?v=1" alt="Photo" width="100" height="100" />
}

如果需要对本地图片使用查询字符串,请将该模式添加到配置中:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    localPatterns: [
      {
        pathname: '/assets/**',
        search: '?v=1',
      },
    ],
  },
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    localPatterns: [
      {
        pathname: '/assets/**',
        search: '?v=1',
      },
    ],
  },
}

module.exports = nextConfig

minimumCacheTTL 默认值(破坏性变更)#

images.minimumCacheTTL 的默认值已从 60 秒 更改为 4 小时(14400 秒)。这降低了没有 cache-control 头图片的重新验证成本。

对某些 Next.js 用户来说,图片重新验证频繁发生,通常是因为上游源图片缺少 cache-control 头。这导致每 60 秒就进行一次重新验证,增加了 CPU 使用率和成本。

由于大多数图片不会频繁变化,这个较短的间隔并不理想。将默认值设为 4 小时可提供更持久的缓存,同时在需要时仍允许图片每天更新几次。

如果需要之前的行为,请将 minimumCacheTTL 设置为较低的值,例如恢复为 60 秒:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    minimumCacheTTL: 60,
  },
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    minimumCacheTTL: 60,
  },
}

module.exports = nextConfig

imageSizes 默认值(破坏性变更)#

值 16 已从默认 images.imageSizes 数组中移除。

我们查看了请求分析数据,发现很少有项目会提供 16 像素宽的图片。移除此设置可减小 next/image 发送到浏览器的 srcset 属性大小。

如果需要支持 16px 图片:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
  },
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
  },
}

module.exports = nextConfig

我们认为与其说开发者不使用,不如说 16 像素宽的图片已变得不那么常见,因为 devicePixelRatio: 2 实际上会获取 32px 的图片以防止在视网膜屏幕上模糊。

qualities 默认值(破坏性变更)#

images.qualities 的默认值已从允许所有质量更改为仅 [75]。

如果需要支持多个质量级别:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    qualities: [50, 75, 100],
  },
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    qualities: [50, 75, 100],
  },
}

module.exports = nextConfig

如果指定的 quality 属性不在 images.qualities 数组中,该质量将被强制转换为 images.qualities 中最接近的值。例如,对于上述配置,quality 属性为 80 时会被强制转换为 75。

检查自定义图片质量。将所需值添加到 images.qualities,并测试直接的 /_next/image 请求,因为不支持的 q 值会返回 400。

本地 IP 限制(破坏性变更)#

新的安全限制默认阻止本地 IP 优化。仅对私有网络将 images.dangerouslyAllowLocalIP 设置为 true。

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    dangerouslyAllowLocalIP: true, // 仅用于私有网络
  },
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    dangerouslyAllowLocalIP: true, // 仅用于私有网络
  },
}

module.exports = nextConfig

当在具有水平分割 DNS 的 VPC 中托管 Next.js 并收到 400 Bad Request 状态时,可能需要这样做。只有在了解 SSRF 风险后才启用。

最大重定向次数(破坏性变更)#

images.maximumRedirects 的默认值已从无限制更改为最多 3 次重定向。

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    maximumRedirects: 0, // 禁用重定向
    // 或者
    maximumRedirects: 5, // 针对边缘情况增加
  },
}

export default nextConfig
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    maximumRedirects: 0, // 禁用重定向
    // 或者
    maximumRedirects: 5, // 针对边缘情况增加
  },
}

module.exports = nextConfig

next/legacy/image 组件(已弃用)#

next/legacy/image 组件已弃用。请改用 next/image:

tsx
// 之前
import Image from 'next/legacy/image'

// 之后
import Image from 'next/image'

images.domains 配置(已弃用)#

images.domains 配置已弃用。

next.config.js
// image.domains 已弃用
module.exports = {
  images: {
    domains: ['example.com'],
  },
}

请改用 images.remotePatterns 以提高安全性:

next.config.js
// 请改用 image.remotePatterns
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
      },
    ],
  },
}

并发运行 dev 和 build#

next dev 和 next build 现在使用不同的输出目录,从而支持并发执行。next dev 命令输出到 .next/dev。

此外,锁文件机制可防止同一项目上出现多个 next dev 或 next build 实例。

Turbopack 追踪命令应为:

bash · pnpm
pnpm next internal trace .next-profiles/trace-turbopack.bin
bash · npm
npx next internal trace .next-profiles/trace-turbopack.bin
bash · yarn
yarn next internal trace .next-profiles/trace-turbopack.bin
bash · bun
bunx next internal trace .next-profiles/trace-turbopack.bin

Parallel Routes 的 default.js 要求#

所有 parallel route 插槽现在都需要显式的 default.js 文件。缺少它们时构建将失败。

为保持之前的行为,请创建一个调用 notFound() 或返回 null 的 default.js 文件。

app/@modal/default.tsx
import { notFound } from 'next/navigation'

export default function Default() {
  notFound()
}

或者返回 null:

app/@modal/default.tsx
export default function Default() {
  return null
}

ESLint Flat Config#

@next/eslint-plugin-next 现在默认使用 ESLint Flat Config 格式,与将弃用旧配置支持的 ESLint v10 保持一致。

请务必查看 @next/eslint-plugin-next 插件的 API 参考。

如果仍在使用旧版 .eslintrc 格式,请考虑迁移到 flat config 格式。有关详情,请参阅 ESLint 迁移指南。

滚动行为覆盖#

在以前版本的 Next.js 中,如果你通过 CSS 在 <html> 元素上全局设置了 scroll-behavior: smooth,Next.js 会在 SPA 路由过渡期间覆盖此设置,过程如下:

  1. 临时将 scroll-behavior 设置为 auto
  2. 执行导航(导致立即滚动到顶部)
  3. 恢复原来的 scroll-behavior 值

这确保页面导航始终感觉轻快即时,即使你为页内导航启用了平滑滚动。不过,这种操作可能开销较大,尤其是在每次导航开始时。

在 Next.js 16 中,此行为已改变。默认情况下,Next.js 在导航期间将不再覆盖你的 scroll-behavior 设置。

如果你希望 Next.js 执行此覆盖(之前的默认行为),请在 <html> 元素上添加 data-scroll-behavior="smooth" 属性:

app/layout.tsx
export default function RootLayout({ children }) {
  return (
    <html lang="en" data-scroll-behavior="smooth">
      <body>{children}</body>
    </html>
  )
}
pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en" data-scroll-behavior="smooth">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

性能改进#

对 next dev 和 next start 命令进行了重大性能优化,同时改进了终端输出,包括更清晰的格式、更好的错误信息和改进的性能指标。

Next.js 16 从 next build 输出中移除了 size 和 First Load JS 指标。我们发现这些指标在使用 React Server Components 的服务端驱动架构中并不准确。我们的 Turbopack 和 Webpack 实现都存在问题,并且在如何计算 Client Components 载荷方面存在分歧。

衡量实际路由性能最有效的方法是使用 Chrome Lighthouse 或 Vercel Analytics 等工具,它们关注 Core Web Vitals 和下载资源大小。

next dev 配置加载#

在以前的版本中,开发期间 Next 配置文件会被加载两次:

  • 运行 next dev 命令时
  • next dev 命令启动 Next.js 服务端时

这很低效,因为 next dev 命令启动 Next.js 服务端并不需要配置文件。

此更改的一个结果是,在运行 next dev 时,在 Next.js 配置文件中检查 process.argv 是否包含 'dev' 将返回 false。

小知识:typegen 和 build 命令仍可在 process.argv 中看到。

这对于在 next dev 时触发副作用的插件尤其重要。如果是这种情况,检查 NODE_ENV 是否设置为 development 可能就足够了。

next.config.js
import { startServer } from 'docs-lib/dev-server'

const isDev = process.env.NODE_ENV === 'development'

if (isDev) {
  startServer()
}

const nextConfig = {
  /* 你的配置项 */
}

module.exports = nextConfig

或者,使用加载配置时的 phase。

Build Adapters API(alpha)#

继 Build Adapters RFC 之后,Build Adapters API 的首个 alpha 版本现已推出。

Build Adapters 允许你创建挂接到构建过程的自定义适配器,使部署平台和自定义构建集成能够修改 Next.js 配置或处理构建输出。

next.config.js
const nextConfig = {
  experimental: {
    adapterPath: require.resolve('./my-adapter.js'),
  },
}

module.exports = nextConfig

adapterPath 在 16.2.0 中已提升为稳定的顶层选项。有关当前的 API 参考,请参阅 adapterPath。

现代 Sass API#

sass-loader 已升级到 v16,支持现代 Sass 语法和新功能。

移除的功能#

以下功能此前已弃用,现已被移除:

AMP 支持#

AMP 的采用率已大幅下降,维护此功能会增加框架的复杂性。所有 AMP API 和配置都已被移除:

  • Next 配置文件中的 amp 配置
  • next/amp hook 的导入和使用(useAmp)
tsx
// 已移除
import { useAmp } from 'next/amp'

// 已移除
export const config = { amp: true }
  • 页面中的 export const config = { amp: true }
next.config.js
const nextConfig = {
  // 已移除
  amp: {
    canonicalBase: 'https://example.com',
  },
}

module.exports = nextConfig

请评估你的用例是否仍需要 AMP。现在大多数性能收益都可以通过 Next.js 的内置优化和现代 Web 标准实现。

next lint 命令#

next lint 命令已被移除。请直接使用 Biome 或 ESLint。next build 不再运行 lint 检查。

可以使用 codemod 自动完成迁移:

bash · pnpm
pnpm dlx @next/codemod@canary next-lint-to-eslint-cli .
bash · npm
npx @next/codemod@canary next-lint-to-eslint-cli .
bash · yarn
yarn dlx @next/codemod@canary next-lint-to-eslint-cli .
bash · bun
bunx @next/codemod@canary next-lint-to-eslint-cli .

Next.js 配置文件中的 eslint 选项也已被移除。

next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  // 不再支持
  // eslint: {},
}

export default nextConfig

运行时配置#

serverRuntimeConfig 和 publicRuntimeConfig 已被移除。请改用环境变量。

之前(Next.js 15):

next.config.js
module.exports = {
  serverRuntimeConfig: {
    dbUrl: process.env.DATABASE_URL,
  },
  publicRuntimeConfig: {
    apiUrl: '/api',
  },
}
pages/index.tsx
import getConfig from 'next/config'

export default function Page() {
  const { publicRuntimeConfig } = getConfig()
  return <p>API URL: {publicRuntimeConfig.apiUrl}</p>
}

之后(Next.js 16):

对于仅限服务端使用的值,请直接在 Server Components 中访问环境变量:

app/page.tsx
async function fetchData() {
  const dbUrl = process.env.DATABASE_URL
  // 仅用于服务端操作
  return await db.query(dbUrl, 'SELECT * FROM users')
}

export default async function Page() {
  const data = await fetchData()
  return <div></div>
}

小知识:使用 taint API 可防止意外将敏感的服务端值传递给 Client Components。

对于客户端可访问的值,请使用 NEXT_PUBLIC_ 前缀:

.env.local
NEXT_PUBLIC_API_URL="/api"
app/components/client-component.tsx
'use client'

export default function ClientComponent() {
  const apiUrl = process.env.NEXT_PUBLIC_API_URL
  return <p>API URL: {apiUrl}</p>
}

为确保环境变量在运行时读取(而不是在构建时打包),请在读取 process.env 之前使用 connection() 函数:

app/page.tsx
import { connection } from 'next/server'

export default async function Page() {
  await connection()
  const config = process.env.RUNTIME_CONFIG
  return <p>{config}</p>
}

了解更多关于环境变量的信息。

devIndicators 选项#

以下选项已从 devIndicators 中移除:

  • appIsrStatus
  • buildActivity
  • buildActivityPosition

该指示器本身仍然可用。

experimental.dynamicIO 和 experimental.useCache#

experimental.dynamicIO 和 experimental.useCache 标志已被移除。

next.config.js
// 之前:experimental.useCache
module.exports = {
  experimental: {
    useCache: true,
  },
}
next.config.js
// 之前:experimental.dynamicIO
module.exports = {
  experimental: {
    dynamicIO: true,
  },
}

如果你一直在积极使用这些标志,请迁移到顶层 cacheComponents:

next.config.ts
import type { NextConfig } from 'next'

// 之后
const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig
next.config.js
// 之后
module.exports = {
  cacheComponents: true,
}

如果你并未积极采用 Cache Components,请直接移除这些标志。启用 cacheComponents 并非单纯的更名:它可能会暴露 <Suspense> 之外未缓存数据导致的构建错误,并要求采用 Cache Components 模型。

有关完整迁移路径,请参阅迁移到 Cache Components。

unstable_rootParams#

unstable_rootParams 函数已被移除。请改用 next/root-params。

Next.js 16 中移除的其他实验性标志#

以下实验性标志在 Next.js 16 的后续次要版本中被移除。升级到相应版本时,请将其从 Next 配置中删除。

标志版本历史迁移
experimental.viewTransition在 15.2.0 中引入,在 16.3.0 中移除。移除该标志。View Transitions 在 App Router 中无需配置即可工作。
experimental.appNewScrollHandler在 16.2.0 中引入,在 16.3.0 中默认启用,并在 16.4.0 中移除。移除该标志。true 值已与默认值一致。false 退出选项不再可用,新的处理器保持焦点不变。

故障排查#

升级到 React 19 后安装失败#

升级 ESLint 后安装失败#

Next.js 16 移除了 next lint,但迁移到 ESLint CLI 并不需要升级 ESLint。eslint-config-next@16 要求 ESLint 9 或更高版本,而 eslint-config-next@16.4.0 或更高版本支持 ESLint 10。如果你现有的 lint 配置未使用 eslint-config-next@16,可以保留其兼容的 ESLint 版本。

  • 如果升级 ESLint 导致 peer dependency 冲突,请恢复 eslint、eslint-config-next 和 @next/eslint-plugin-next(如果存在)之前兼容的版本,以及之前的 lint 配置。
  • 如果安装中断了升级,请使用 --skip-eslint-upgrade 重试完全相同的目标,以保留修复后的 lint 技术栈并跳过 lint codemod。如果 Next.js 已与目标版本一致,请安装依赖项并单独完成中断的迁移。将 next lint 脚本替换为与保留配置兼容的 ESLint CLI 命令。确认安装和 lint 均通过。

检查迁移清单#

在应用与你的项目相关的更改后,请在认为迁移完成之前检查以下事项:

  • 应用满足本指南中的 Node.js、TypeScript 和 React 要求。
  • 开发和构建脚本与实际的打包器配置一致,包括插件、loader、别名以及受影响的 Sass 导入。
  • Middleware 和 proxy 的更改保留了所需的运行时和路由行为。Edge middleware 未被盲目重命名为 proxy。
  • 受影响的图片请求在文档所述的限制和默认设置下成功,同时保持预期质量。
  • 现有的缓存 API 调用遵循文档所述的签名和语义。React Compiler 和 Cache Components 并非仅为完成升级而启用。
  • 已移除的 API 和配置不再有任何使用者。运行时配置的替代方案保留了服务端和客户端的可见性以及所需的求值时机。
  • 脚本和 CI 不再调用 next lint;在应用需要的地方单独运行 lint 检查。
  • 应用支持的检查和受影响的运行时行为均通过。仅构建成功并不意味着运行时问题已解决。
  • 异步 Request API 的访问和受影响调用方已完成迁移。解决 codemod 错误注释和 UnsafeUnwrapped 强制转换;在适当的情况下,对同步 Client Components 使用 React use。
  • 动态元数据图片函数和 sitemap 函数处理其异步参数,受影响的生成 URL 正常工作。
  • Parallel route 插槽具有适当的默认值,直接导航和重新加载保留预期的后备行为。
Next.js 中文网