主题
版本 16
¥Version 16
从 15 升级到 16
¥Upgrading from 15 to 16
在 Next.js DevTools MCP 中使用 AI 代理
¥Using AI Agents with Next.js DevTools MCP
如果你使用支持 模型上下文协议 (MCP) 的 AI 代码助手,可以使用 Next.js DevTools MCP 来自动化升级过程和迁移任务。
¥If you're using an AI coding assistant that supports the Model Context Protocol (MCP), you can use the Next.js DevTools MCP to automate the upgrade process and migration tasks.
设置
¥Setup
将以下配置添加到你的 MCP 客户端,例如:
¥Add the following configuration to your MCP client, example:
更多信息,请访问 npm 上的 next-devtools-mcp 包,以便使用你的 MCP 客户端进行配置。
¥For more information, visit the next-devtools-mcp package on npm to configure with your MCP client.
注意:使用
next-devtools-mcp@latest可确保你的 MCP 客户端始终使用最新版本的 Next.js DevTools MCP 服务器。¥Note: Using
next-devtools-mcp@latestensures that your MCP client will always use the latest version of the Next.js DevTools MCP server.
示例提示
¥Example Prompts
配置完成后,你可以使用自然语言提示来升级你的 Next.js 应用:
¥Once configured, you can use natural language prompts to upgrade your Next.js app:
要升级到 Next.js 16:
¥To upgrade to Next.js 16:
连接到你的编码代理,然后提示:
¥Connect to your coding agent and then prompt:
txt
Next Devtools, help me upgrade my Next.js app to version 16要迁移到缓存组件(升级到 v16 后):
¥To migrate to Cache Components (after upgrading to v16):
连接到你的编码代理,然后提示:
¥Connect to your coding agent and then prompt:
txt
Next Devtools, migrate my Next.js app to cache components在文档 此处 中了解更多信息。
¥Learn more in the documentation here.
使用 Codemod
¥Using the Codemod
要更新到 Next.js 版本 16,你可以使用 upgrade 或 codemod:
¥To update to Next.js version 16, you can use the upgrade codemod:
bash
npx @next/codemod@canary upgrade latestcodemod 能够:
¥The codemod is able to:
更新
next.config.js以使用新的turbopack配置¥Update
next.config.jsto use the newturbopackconfiguration从
next lint迁移到 ESLint CLI。¥Migrate from
next lintto the ESLint CLI从已弃用的
middleware约定迁移到proxy¥Migrate from deprecated
middlewareconvention toproxy从稳定 API 中移除
unstable_前缀¥Remove
unstable_prefix from stabilized APIs从页面和布局中移除
experimental_ppr路由段配置¥Remove
experimental_pprRoute Segment Config from pages and layouts
如果你更喜欢手动操作,请安装最新版本的 Next.js 和 React:
¥If you prefer to do it manually, install the latest Next.js and React versions:
bash
npm install next@latest react@latest react-dom@latest如果你使用 TypeScript,请确保还将 @types/react 和 @types/react-dom 升级到最新版本。
¥If you are using TypeScript, ensure you also upgrade @types/react and @types/react-dom to their latest versions.
Node.js 运行时和浏览器支持
¥Node.js runtime and browser support
| 要求 | 更改/详情 |
|---|---|
| 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
¥Turbopack by default
从 Next.js 16 开始,Turbopack 已稳定,并默认与 next dev 和 next build 一起使用。
¥Starting with Next.js 16, Turbopack is stable and used by default with next dev and next build
以前,你必须使用 --turbopack 或 --turbo 启用 Turbopack。
¥Previously you had to enable Turbopack using --turbopack, or --turbo.
这已不再必要。你可以更新 package.json 脚本:
¥This is no longer necessary. You can update your package.json scripts:
如果你的项目使用了 定制 webpack 配置,而你运行的是 next build(现在默认使用 Turbopack),则构建会失败,以防止配置错误。
¥If your project has a custom webpack configuration and you run next build (which now uses Turbopack by default), the build will fail to prevent misconfiguration issues.
你可以通过几种不同的方式来实现这一点:
¥You have a few different ways to address this:
始终使用 Turbopack:运行
next build --turbopack可使用 Turbopack 构建,并忽略webpack配置。¥Use Turbopack anyway: Run with
next build --turbopackto build using Turbopack and ignore yourwebpackconfig.完全切换到 Turbopack:将
webpack配置迁移到与 Turbopack 兼容的选项。¥Switch to Turbopack fully: Migrate your
webpackconfig to Turbopack-compatible options.继续使用 Webpack:使用
--webpack标志选择不使用 Turbopack,而是使用 Webpack 构建。¥Keep using Webpack: Use the
--webpackflag to opt out of Turbopack and build with Webpack.
需要了解:如果你发现构建失败,原因是找到了
webpack配置,但你自己并未定义webpack配置,则可能是某个插件添加了webpack选项。¥Good to know: If you see failing builds because a
webpackconfiguration was found, but you don't define one yourself, it is likely that a plugin is adding awebpackoption
选择退出 Turbopack
¥Opting out of Turbopack
如果你需要继续使用 Webpack,可以使用 --webpack 标志选择退出。例如,要在开发环境中使用 Turbopack,而在生产环境中使用 Webpack:
¥If you need to continue using Webpack, you can opt out with the --webpack flag. For example, to use Turbopack in development but Webpack for production builds:
我们建议在开发和生产环境中使用 Turbopack。如果你无法切换到 Turbopack,请在此 thread 标签下提交评论。
¥We recommend using Turbopack for development and production. Submit a comment to this thread, if you are unable to switch to Turbopack.
Turbopack 配置位置
¥Turbopack configuration location
experimental.turbopack 配置已结束实验阶段。
¥The experimental.turbopack configuration is out of experimental.
ts
import type { NextConfig } from 'next'
// Next.js 15 - experimental.turbopack
const nextConfig: NextConfig = {
experimental: {
turbopack: {
// options
},
},
}
export default nextConfig你可以将其用作顶层 turbopack 选项:
¥You can use it as a top-level turbopack option:
ts
import type { NextConfig } from 'next'
// Next.js 16 - turbopack at the top level of nextConfig
const nextConfig: NextConfig = {
turbopack: {
// options
},
}
export default nextConfig请务必查看 Turbopack 配置 options。Next.js 16 引入了多项改进和新选项,例如:
¥Make sure to review the Turbopack configuration options. Next.js 16 introduces various improvements and new options, for example:
解析别名回退
¥Resolve alias fallback
在某些项目中,客户端代码可能会导入包含 Node.js 原生模块的文件。这将导致 Module not found: Can't resolve 'fs' 类型的错误。
¥In some projects, client-side code may import files containing Node.js native modules. This will cause Module not found: Can't resolve 'fs' type of errors.
发生这种情况时,你应该重构代码,使客户端包不再引用这些 Node.js 原生模块。
¥When this happens, you should refactor your code so that your client-side bundles do not reference these Node.js native modules.
然而,在某些情况下,这可能无法实现。在 Webpack 中,resolve.fallback 选项通常用于抑制错误。Turbopack 提供类似的功能,使用 turbopack.resolveAlias。在这种情况下,告诉 Turbopack 在浏览器请求 fs 时加载一个空模块。
¥However, in some cases, this might not be possible. In Webpack the resolve.fallback option was typically used to silence the error. Turbopack offers a similar option, using turbopack.resolveAlias. In this case, tell Turbopack to load an empty module when fs is requested for the browser.
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
resolveAlias: {
fs: {
browser: './empty.ts', // We recommend to fix code imports before using this method
},
},
},
}
export default nextConfig最好重构你的模块,使客户端代码永远不要从使用 Node.js 原生模块的模块导入。
¥It is preferable to refactor your modules so that client code doesn't ever import from modules using Node.js native modules.
Sass node_modules 导入
¥Sass node_modules imports
Turbopack 完全支持从 node_modules 导入 Sass 文件。请注意,虽然 Webpack 允许使用旧式波浪号 (~) 前缀,但 Turbopack 不支持此语法。
¥Turbopack fully supports importing Sass files from node_modules. Note that while Webpack allowed the legacy tilde (~) prefix, Turbopack does not support this syntax.
在 Webpack 中:
¥In Webpack:
scss
@import '~bootstrap/dist/css/bootstrap.min.css';在 Turbopack 中:
¥In Turbopack:
scss
@import 'bootstrap/dist/css/bootstrap.min.css';如果无法更改导入,则可以使用 turbopack.resolveAlias。例如:
¥If changing the imports is not possible, you can use turbopack.resolveAlias. For example:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
resolveAlias: {
'~*': '*',
},
},
}
export default nextConfigTurbopack 文件系统缓存(测试版)
¥Turbopack File System Caching (beta)
Turbopack 现在支持在开发环境中使用文件系统缓存,将编译器生成的工件存储在磁盘上,从而显著加快重启后的编译速度。
¥Turbopack now supports filesystem caching in development, storing compiler artifacts on disk between runs for significantly faster compile times across restarts.
在配置中启用文件系统缓存。
¥Enable filesystem caching in your configuration:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
turbopackFileSystemCacheForDev: true,
},
}
export default nextConfig异步请求 API(重大更改)
¥Async Request APIs (Breaking change)
版本 15 引入了 异步请求 API,这是一个重大变更,但提供了临时的同步兼容性。
¥Version 15 introduced Async Request APIs as a breaking change, with temporary synchronous compatibility.
从 Next.js 16 开始,同步访问已被完全移除。这些 API 只能异步访问。
¥Starting with Next.js 16, synchronous access is fully removed. These APIs can only be accessed asynchronously.
layout.js、page.js、route.js、default.js、opengraph-image、twitter-image、icon和apple-icon中的params。¥
paramsinlayout.js,page.js,route.js,default.js,opengraph-image,twitter-image,icon, andapple-icon.searchParams于page.js¥
searchParamsinpage.js
使用 codemod 迁移到异步动态 API。
¥Use the codemod to migrate to async Dynamic APIs.
迁移异步动态 API 的类型
¥Migrating types for async Dynamic APIs
为了帮助你迁移到异步 params 和 searchParams,你可以运行 npx next typegen 来自动生成这些全局可用的类型辅助函数:
¥To help migrate to async params and searchParams, you can run npx next typegen to automatically generate these globally available types helpers:
需要了解:
typegen在 Next.js 15.5 中引入。¥Good to know:
typegenwas introduced in Next.js 15.5
这简化了向新的异步 API 模式进行类型安全迁移的过程,并使你能够以完全的类型安全方式更新组件,例如:
¥This simplifies type-safe migration to the new async API pattern, and enables you to update your components with full type safety, for example:
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。
¥This approach gives you fully type-safe access to props.params, including the slug, and to searchParams, directly within your page.
图标和 Open Graph 图片的异步参数(重大变更)
¥Async parameters for icon, and open-graph Image (Breaking change)
传递给
opengraph-image、twitter-image、icon和apple-icon中图片生成函数的 props 现在都是 Promise。¥The props passed to the image generating functions in
opengraph-image,twitter-image,icon, andapple-icon, are now Promises.
在之前的版本中,Image(图片生成函数)和 generateImageMetadata 都会接收一个 params 对象。generateImageMetadata 返回的 id 已作为字符串传递给图片生成函数。
¥In previous versions, both the Image (image generation function), and the generateImageMetadata received a params object. The id returned by generateImageMetadata was passed as a string to the image generation function.
从 Next.js 16 开始,为了与 异步请求 API 的变更保持一致,图片生成函数现在接收 params 和 id 作为 Promise。generateImageMetadata 函数继续接收同步的 params。
¥Starting with Next.js 16, to align with the Async Request APIs change, the image generating function now receives params and id as promises. The generateImageMetadata function continues to receive synchronous params.
sitemap 的异步 id 参数(重大变更)
¥Async id parameter for sitemap (Breaking change)
以前,从 generateSitemaps 返回的 id 值会直接传递给 sitemap 生成函数。
¥Previously, the id values returned from generateSitemaps were passed directly to the sitemap generating function.
从 Next.js 16 开始,sitemap 生成函数现在接收 id 作为 Promise。
¥Starting with Next.js 16, the sitemap generating function now receives id as a promise.
React 19.2
Next.js 16 中的应用路由使用最新的 React Canary 版本发布,其中包含新发布的 React 19.2 特性以及其他正在逐步稳定化的特性。亮点包括:
¥The App Router in Next.js 16 uses the latest React Canary release, which includes the newly released React 19.2 features and other features being incrementally stabilized. Highlights include:
视图过渡:为在 Transition 或导航中更新的元素添加动画效果
¥View Transitions: Animate elements that update inside a Transition or navigation
useEffectEvent:将 Effects 中的非响应式逻辑提取到可重用的 Effect Event 函数中¥
useEffectEvent: Extract non-reactive logic from Effects into reusable Effect Event functionsActivity:使用
display: none隐藏 UI 并渲染 "后台活动",同时保持状态并清理 Effects¥Activity: Render "background activity" by hiding UI with
display: nonewhile maintaining state and cleaning up Effects
在 React 19.2 公告 中了解更多信息。
¥Learn more in the React 19.2 announcement.
React 编译器支持
¥React Compiler Support
随着 React 编译器 1.0 版本的发布,Next.js 16 中对 React 编译器的内置支持现已稳定。React 编译器会自动缓存组件,无需任何手动代码更改即可减少不必要的重新渲染。
¥Built-in support for the React Compiler is now stable in Next.js 16 following the React Compiler's 1.0 release. The React Compiler automatically memoizes components, reducing unnecessary re-renders with zero manual code changes.
reactCompiler 配置选项已从 experimental 升级到稳定版。由于我们仍在收集不同应用类型的构建性能数据,因此默认情况下未启用此功能。
¥The reactCompiler configuration option has been promoted from experimental to stable. It is not enabled by default as we continue gathering build performance data across different application types.
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: true,
}
export default nextConfig安装最新版本的 React Compiler 插件:
¥Install the latest version of the React Compiler plugin:
bash
npm install -D babel-plugin-react-compiler需要了解:启用此选项后,开发和构建过程中的编译时间预计会更长,因为 React 编译器依赖于 Babel。
¥Good to know: Expect compile times in development and during builds to be higher when enabling this option as the React Compiler relies on Babel.
缓存 API
¥Caching APIs
revalidateTag
revalidateTag 具有新的函数签名。你可以将 cacheLife 配置作为第二个参数传递。
¥revalidateTag has a new function signature. You can pass a cacheLife profile as the second argument.
ts
'use server'
import { revalidateTag } from 'next/cache'
export async function updateArticle(articleId: string) {
// Mark article data as stale - article readers see stale data while it revalidates
revalidateTag(`article-${articleId}`, 'max')
}对于允许略微延迟更新的内容,例如博客文章、产品目录或文档,请使用 revalidateTag。用户会收到过时的内容,同时后台会加载新数据。
¥Use revalidateTag for content where a slight delay in updates is acceptable, such as blog posts, product catalogs, or documentation. Users receive stale content while fresh data loads in the background.
updateTag
updateTag 是一个仅适用于 服务器操作 的全新 API,它提供读写语义,用户进行更改后,UI 会立即显示更改后的数据,而不是显示过时的数据。
¥updateTag is a new Server Actions-only API that provides read-your-writes semantics, where a user makes a change and the UI immediately shows the change, rather than stale data.
它通过在同一请求中使数据过期并立即刷新来实现这一点。
¥It does this by expiring and immediately refreshing data within the same request.
ts
'use server'
import { updateTag } from 'next/cache'
export async function updateUserProfile(userId: string, profile: Profile) {
await db.users.update(userId, profile)
// Expire cache and refresh immediately - user sees their changes right away
updateTag(`user-${userId}`)
}这确保了交互功能能够立即反映更改。非常适合表单、用户设置以及任何用户希望立即看到更新的工作流程。
¥This ensures interactive features reflect changes immediately. Perfect for forms, user settings, and any workflow where users expect to see their updates instantly.
了解更多关于何时使用 updateTag 或 revalidateTag 此处 的信息。
¥Learn more about when to use updateTag or revalidateTag here.
refresh
refresh 允许你从服务器操作中刷新客户端路由。
¥refresh allows you to refresh the client router from within a Server Action.
ts
'use server'
import { refresh } from 'next/cache'
export async function markNotificationAsRead(notificationId: string) {
// Update the notification in the database
await db.notifications.markAsRead(notificationId)
// Refresh the notification count displayed in the header
refresh()
}在执行操作后需要刷新客户端路由时使用。
¥Use it when you need to refresh the client router after performing an action.
cacheLife 和 cacheTag
¥cacheLife and cacheTag
cacheLife 和 cacheTag 现在已稳定。不再需要 unstable_ 前缀。
¥cacheLife and cacheTag are now stable. The unstable_ prefix is no longer needed.
无论你之前使用了别名导入,例如:
¥Wherever you had aliased imports like:
ts
import {
unstable_cacheLife as cacheLife,
unstable_cacheTag as cacheTag,
} from 'next/cache'你可以更新导入语句:
¥You can update your imports to:
ts
import { cacheLife, cacheTag } from 'next/cache'增强的路由和导航
¥Enhanced Routing and Navigation
Next.js 16 对路由和导航系统进行了全面改进,使页面切换更加简洁快速。这优化了 Next.js 预取和缓存导航数据的方式:
¥Next.js 16 includes a complete overhaul of the routing and navigation system, making page transitions leaner and faster. This optimizes how Next.js prefetches and caches navigation data:
布局去重:使用共享布局预取多个 URL 时,布局只会下载一次。
¥Layout deduplication: When prefetching multiple URLs with a shared layout, the layout is downloaded once.
增量预取:Next.js 仅预取缓存中尚未包含的部分内容,而不是整个页面。
¥Incremental prefetching: Next.js only prefetches parts not already in cache, rather than entire pages.
这些更改无需修改任何代码,旨在提升所有应用的性能。
¥These changes require no code modifications and are designed to improve performance across all apps.
但是,你可能会看到更多单独的预取请求,但总传输大小却小得多。我们认为这对于几乎所有应用来说都是合适的折衷方案。
¥However, you may see more individual prefetch requests with much lower total transfer sizes. We believe this is the right trade-off for nearly all applications.
如果请求数量增加导致问题,请通过创建 issue 或 discussion 条目告知我们。
¥If the increased request count causes issues, please let us know by creating an issue or discussion item.
部分预渲染 (PPR)
¥Partial Pre-Rendering (PPR)
Next.js 16 移除了实验性的局部预渲染 (PPR) 标志和配置选项,包括路由级别的 experimental_ppr 段。
¥Next.js 16 removes the experimental Partial Pre-Rendering (PPR) flag and configuration options, including the route level segment experimental_ppr.
从 Next.js 16 开始,你可以使用 cacheComponents 配置启用 PPR(预渲染)。
¥Starting with Next.js 16, you can opt into PPR using the cacheComponents configuration.
Next.js 16 中的 PPR 与 Next.js 15 canary 版本中的 PPR 工作方式不同。如果你目前正在使用 PPR,请继续使用你当前正在使用的 Next.js 15 Canary 版本。我们将发布一份迁移到缓存组件的指南。
¥PPR in Next.js 16 works differently than in Next.js 15 canaries. If you are using PPR today, stay in the current Next.js 15 canary you are using. We will follow up with a guide to migrate to Cache Components.
从 middleware 到 proxy
¥middleware to proxy
middleware 文件名已弃用,并已重命名为 proxy,以明确网络边界和路由的重点。
¥The middleware filename is deprecated, and has been renamed to proxy to clarify network boundary and routing focus.
proxy 不支持 edge 运行时。proxy 运行时即为 nodejs,且无法配置。如果你希望继续使用 edge 运行时,请继续使用 middleware。我们将在后续的小版本更新中提供更多关于 edge 运行时的说明。
¥The edge runtime is NOT supported in proxy. The proxy runtime is nodejs, and it cannot be configured. If you want to continue using the edge runtime, keep using middleware. We will follow up on a minor release with further edge runtime instructions.
bash
# Rename your middleware file
mv middleware.ts proxy.ts
# or
mv middleware.js proxy.js命名导出 middleware 也已弃用。将你的函数重命名为 proxy。
¥The named export middleware is also deprecated. Rename your function to proxy.
ts
export function proxy(request: Request) {}我们建议将函数名更改为 proxy,即使你使用的是默认导出。
¥We recommend changing the function name to proxy, even if you are using a default export.
包含 middleware 名称的配置标志也会被重命名。例如,skipMiddlewareUrlNormalize 现在等于 skipProxyUrlNormalize
¥Configuration flags that contained the middleware name are also renamed. For example, skipMiddlewareUrlNormalize is now skipProxyUrlNormalize
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
skipProxyUrlNormalize: true,
}
export default nextConfig版本 16 的 codemod 也能够更新这些标志。
¥The version 16 codemod is able to update these flags too.
next/image 的更改
¥next/image changes
带有查询字符串的本地图片(重大变更)
¥Local Images with Query Strings (Breaking change)
带有查询字符串的本地图片源现在需要 images.localPatterns.search 配置,以防止枚举攻击。
¥Local image sources with query strings now require images.localPatterns.search configuration to prevent enumeration attacks.
tsx
import Image from 'next/image'
export default function Page() {
return <Image src="/assets/photo?v=1" alt="Photo" width="100" height="100" />
}如果你需要对本地图片使用查询字符串,请将以下模式添加到你的配置中:
¥If you need to use query strings with local images, add the pattern to your configuration:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
localPatterns: [
{
pathname: '/assets/**',
search: '?v=1',
},
],
},
}
export default nextConfigminimumCacheTTL 默认(重大变更)
¥minimumCacheTTL Default (Breaking change)
images.minimumCacheTTL 的默认值已从 60 seconds 更改为 4 hours(14400 秒)。此模式可降低没有缓存控制标头的图片的重新验证成本。
¥The default value for images.minimumCacheTTL has changed from 60 seconds to 4 hours (14400 seconds). This reduces revalidation cost for images without cache-control headers.
对于某些 Next.js 用户,图片重新验证频繁发生,通常是因为上游源图片缺少 cache-control 标头。这导致每 60 秒进行一次重新验证,从而增加了 CPU 使用率和成本。
¥For some Next.js users, image revalidation was happening frequently, often because the upstream source images missed a cache-control header. This caused revalidation to happen every 60 seconds, which increased CPU usage and cost.
由于大多数图片不会频繁更改,因此这种较短的间隔并不理想。默认设置为 4 小时可提供更持久的缓存,同时仍允许图片在需要时每天更新几次。
¥Since most images do not change often, this short interval is not ideal. Setting the default to 4 hours offers a more durable cache by default, while still allowing images to update a few times per day if needed.
如果你需要恢复之前的行为,请将 minimumCacheTTL 的值降低,例如改回 60 秒:
¥If you need the previous behavior, change minimumCacheTTL to a lower value, for example back to 60 seconds:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
minimumCacheTTL: 60,
},
}
export default nextConfigimageSizes 默认(重大变更)
¥imageSizes Default (Breaking change)
值 16 已从默认的 images.imageSizes 数组中移除。
¥The value 16 has been removed from the default images.imageSizes array.
我们查看了请求分析,发现很少有项目会提供 16 像素宽的图片。移除此设置可减小 next/image 发送到浏览器的 srcset 属性的大小。
¥We have looked at request analytics and found out that very few projects ever serve 16 pixels width images. Removing this setting reduces the size of the srcset attribute shipped to the browser by next/image.
如果你需要支持 16px 图片:
¥If you need to support 16px images:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
export default nextConfig我们认为,16 像素宽的图片不再常见并非因为开发者使用率低,而是因为 devicePixelRatio: 2 实际上会获取 32 像素宽的图片,以防止在视网膜显示屏上出现模糊。
¥Rather than lack of developer usage, we believe 16 pixels width images have become less common, because devicePixelRatio: 2 actually fetches a 32px image to prevent blurriness in retina displays.
qualities 默认(重大变更)
¥qualities Default (Breaking change)
images.qualities 的默认值已从允许所有属性更改为仅允许 [75]。
¥The default value for images.qualities has changed from allowing all qualities to only [75].
如果你需要支持多种质量级别:
¥If you need to support multiple quality levels:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
qualities: [50, 75, 100],
},
}
export default nextConfig如果你指定了 image.qualities 数组中未包含的 quality 属性,则质量值将被强制转换为 images.qualities 中最接近的值。例如,根据上述配置,quality 属性值为 80 时,会被强制转换为 75。
¥If you specify a quality prop not included in the image.qualities array, the quality will be coerced to the closest value in images.qualities. For example, given the configuration above, a quality prop of 80, is coerced to 75.
本地 IP 限制(重大变更)
¥Local IP Restriction (Breaking change)
一项新的安全限制默认阻止本地 IP 优化。仅在私有网络中将 images.dangerouslyAllowLocalIP 设置为 true。
¥A new security restriction blocks local IP optimization by default. Set images.dangerouslyAllowLocalIP to true only for private networks.
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
dangerouslyAllowLocalIP: true, // Only for private networks
},
}
export default nextConfig最大重定向次数(重大变更)
¥Maximum Redirects (Breaking change)
images.maximumRedirects 的默认值已从无限制更改为最多 3 次重定向。
¥The default for images.maximumRedirects has changed from unlimited to 3 redirects maximum.
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
maximumRedirects: 0, // Disable redirects
// or
maximumRedirects: 5, // Increase for edge cases
},
}
export default nextConfignext/legacy/image 组件(已弃用)
¥next/legacy/image Component (deprecated)
next/legacy/image 组件已弃用。使用 next/image:
¥The next/legacy/image component is deprecated. Use next/image instead:
tsx
// Before
import Image from 'next/legacy/image'
// After
import Image from 'next/image'images.domains 配置(已弃用)
¥images.domains Configuration (deprecated)
images.domains 配置已弃用。
¥The images.domains config is deprecated.
为了提高安全性,请改用 images.remotePatterns:
¥Use images.remotePatterns instead for improved security:
并发 dev 和 build
¥Concurrent dev and build
next dev 和 next build 现在使用单独的输出目录,从而支持并发执行。next dev 命令的输出会发送到 .next/dev。这是由 isolatedDevBuild 控制的新默认行为。
¥next dev and next build now use separate output directories, enabling concurrent execution. The next dev command outputs to .next/dev. This is the new default behavior, controlled by isolatedDevBuild.
此外,锁定文件机制可防止同一项目上存在多个 next dev 或 next build 实例。
¥Additionally, a lockfile mechanism prevents multiple next dev or next build instances on the same project.
由于开发服务器输出到 .next/dev,因此 Turbopack 跟踪命令 应为:
¥Since the development server outputs to .next/dev, the Turbopack tracing command should be:
bash
npx next internal trace .next/dev/trace-turbopack并行路由 default.js 要求
¥Parallel Routes default.js requirement
所有 并行路由 插槽现在都需要显式的 default.js 文件。如果没有这些参数,构建将会失败。
¥All parallel route slots now require explicit default.js files. Builds will fail without them.
要保持之前的行为,请创建一个调用 notFound() 或返回 null 的 default.js 文件。
¥To maintain previous behavior, create a default.js file that calls notFound() or returns null.
tsx
import { notFound } from 'next/navigation'
export default function Default() {
notFound()
}或返回 null:
¥Or return null:
tsx
export default function Default() {
return null
}ESLint 扁平化配置
¥ESLint Flat Config
@next/eslint-plugin-next 现在默认使用 ESLint Flat Config 格式,与 ESLint v10 保持一致,后者将不再支持旧版配置。
¥@next/eslint-plugin-next now defaults to ESLint Flat Config format, aligning with ESLint v10 which will drop legacy config support.
请务必查看 @next/eslint-plugin-next 插件的 API 参考文档。
¥Make sure to review our API reference for the @next/eslint-plugin-next plugin.
如果你使用的是旧版 .eslintrc 格式,请考虑迁移到扁平配置格式。请参阅 ESLint 迁移指南 获取详细信息。
¥If you're using the legacy .eslintrc format, consider migrating to the flat config format. See the ESLint migration guide for details.
滚动行为重写
¥Scroll Behavior Override
在之前的 Next.js 版本中,如果你通过 CSS 在 <html> 元素上全局设置了 scroll-behavior: smooth,Next.js 会在 SPA 路由转换期间覆盖此设置,如下所示:
¥In previous versions of Next.js, if you had set scroll-behavior: smooth globally on your <html> element via CSS, Next.js would override this during SPA route transitions, as follows:
暂时将
scroll-behavior设置为auto¥Temporarily set
scroll-behaviortoauto执行导航(导致页面立即滚动到顶部)。
¥Perform the navigation (causing instant scroll to top)
恢复原始的
scroll-behavior值。¥Restore your original
scroll-behaviorvalue
这确保了页面导航始终流畅快捷,即使你启用了页面内导航的平滑滚动功能。但是,这种操作可能会消耗大量资源,尤其是在每次导航开始时。
¥This ensured that page navigation always felt snappy and instant, even when you had smooth scrolling enabled for in-page navigation. However, this manipulation could be expensive, especially at the start of every navigation.
在 Next.js 16 中,此行为已更改。默认情况下,Next.js 在导航期间将不再覆盖你的 scroll-behavior 设置。
¥In Next.js 16, this behavior has changed. By default, Next.js will no longer override your scroll-behavior setting during navigation.
如果你希望 Next.js 执行此覆盖(之前的默认行为),请将 data-scroll-behavior="smooth" 属性添加到你的 <html> 元素:
¥If you want Next.js to perform this override (the previous default behavior), add the data-scroll-behavior="smooth" attribute to your <html> element:
tsx
export default function RootLayout({ children }) {
return (
<html lang="en" data-scroll-behavior="smooth">
<body>{children}</body>
</html>
)
}性能改进
¥Performance Improvements
显著优化了 next dev 和 next start 命令的性能,并改进了终端输出,使其格式更清晰、错误信息更完善,性能指标也得到提升。
¥Significant performance optimizations for next dev and next start commands, along with improved terminal output with clearer formatting, better error messages, and improved performance metrics.
Next.js 16 从 next build 输出中移除了 size 和 First Load JS 指标。我们发现,在使用 React Server Components 的服务器驱动架构中,这些值并不准确。我们的 Turbopack 和 Webpack 实现都存在问题,并且在如何处理客户端组件有效负载方面存在分歧。
¥Next.js 16 removes the size and First Load JS metrics from the next build output. We found these to be inaccurate in server-driven architectures using React Server Components. Both our Turbopack and Webpack implementations had issues, and disagreed on how to account for Client Components payload.
衡量实际路由性能的最有效方法是使用 Chrome Lighthouse 或 Vercel Analytics 等工具,这些工具专注于核心 Web 指标和下载的资源大小。
¥The most effective way to measure actual route performance is through tools such as Chrome Lighthouse or Vercel Analytics, which focus on Core Web Vitals and downloaded resource sizes.
next dev 配置加载
¥next dev config load
在之前的版本中,Next 配置文件在开发过程中会被加载两次:
¥In previous versions the Next config file was loaded twice during development:
运行
next dev命令时¥When running the
next devcommand当
next dev命令启动 Next.js 服务器时¥When the
next devcommand started the Next.js server
这种方式效率低下,因为 next dev 命令不需要配置文件即可启动 Next.js 服务器。
¥This was inefficient because the next dev command doesn't need the config file to start the Next.js server.
此更改的后果是,运行 next dev 时,如果 Next.js 配置文件中的 process.argv 包含 'dev',则会返回 false。
¥A consequence of this change is that, when running next dev checking if process.argv includes 'dev', in your Next.js config file, will return false.
需要了解:
typegen和build命令在process.argv中仍然可见。¥Good to know: The
typegen, andbuildcommands, are still visible inprocess.argv.
这对于在 next dev 上触发副作用的插件尤为重要。在这种情况下,检查 NODE_ENV 是否设置为 development 可能就足够了。
¥This is specially important for plugins that trigger side-effects on next dev. If that's the case, it might be enough to check if NODE_ENV is set to development.
或者,使用加载配置的 phase 文件。
¥Alternatively, use the phase in which the configuration is loaded.
构建适配器 API(alpha 版)
¥Build Adapters API (alpha)
继 构建适配器 RFC 之后,构建适配器 API 的第一个 alpha 版本现已发布。
¥Following the Build Adapters RFC, the first alpha version of the Build Adapters API is now available.
构建适配器允许你创建自定义适配器,这些适配器会接入构建过程,从而使部署平台和自定义构建集成能够修改 Next.js 配置或处理构建输出。
¥Build Adapters allow you to create custom adapters that hook into the build process, enabling deployment platforms and custom build integrations to modify Next.js configuration or process build output.
在 RFC 讨论 中分享你的反馈。
¥Share your feedback in the RFC discussion.
现代 Sass API
¥Modern Sass API
sass-loader 已升级至 v16,支持 现代 Sass 语法 和新功能。
¥sass-loader has been bumped to v16, which supports modern Sass syntax and new features.
移除
¥Removals
这些功能之前已被弃用,现已移除:
¥These features were previously deprecated and are now removed:
AMP 支持
¥AMP Support
AMP 的采用率已显著下降,维护此功能会增加框架的复杂性。所有 AMP API 和配置均已移除:
¥AMP adoption has declined significantly, and maintaining this feature adds complexity to the framework. All AMP APIs and configurations have been removed:
来自 Next 配置文件的
amp配置¥
ampconfiguration from your Next config filenext/amphook 导入和用法 (useAmp)¥
next/amphook imports and usage (useAmp)
tsx
// Removed
import { useAmp } from 'next/amp'
// Removed
export const config = { amp: true }从页面调用
export const config = { amp: true }¥
export const config = { amp: true }from pages
评估你的用例是否仍然需要 AMP。现在,大多数性能提升都可以通过 Next.js 的内置优化和现代 Web 标准来实现。
¥Evaluate if AMP is still necessary for your use case. Most performance benefits can now be achieved through Next.js's built-in optimizations and modern web standards.
next lint 命令
¥next lint Command
next lint 命令已被移除。直接使用 Biome 或 ESLint。next build 不再运行代码检查。
¥The next lint command has been removed. Use Biome or ESLint directly. next build no longer runs linting.
提供代码转换工具以自动执行迁移:
¥A codemod is available to automate migration:
bash
npx @next/codemod@canary next-lint-to-eslint-cli .Next.js 配置文件中的 eslint 选项也已被移除。
¥The eslint option in the Next.js config file is also removed.
运行时配置
¥Runtime Configuration
serverRuntimeConfig 和 publicRuntimeConfig 已被移除。使用环境变量。
¥serverRuntimeConfig and publicRuntimeConfig have been removed. Use environment variables instead.
之前(Next.js 15):
¥Before (Next.js 15):
tsx
import getConfig from 'next/config'
export default function Page() {
const { publicRuntimeConfig } = getConfig()
return <p>API URL: {publicRuntimeConfig.apiUrl}</p>
}在 (Next.js 16) 之后:
¥After (Next.js 16):
对于仅限服务器端的值,请直接在服务器组件中访问环境变量:
¥For server-only values, access environment variables directly in Server Components:
tsx
async function fetchData() {
const dbUrl = process.env.DATABASE_URL
// Use for server-side operations only
return await db.query(dbUrl, 'SELECT * FROM users')
}
export default async function Page() {
const data = await fetchData()
return <div>{/* render data */}</div>
}需要了解:使用 taint API 防止意外地将敏感的服务器值传递给客户端组件。
¥Good to know: Use the taint API to prevent accidentally passing sensitive server values to Client Components.
对于客户端可访问的值,请使用 NEXT_PUBLIC_ 前缀:
¥For client-accessible values, use the NEXT_PUBLIC_ prefix:
bash
NEXT_PUBLIC_API_URL="/api"tsx
'use client'
export default function ClientComponent() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL
return <p>API URL: {apiUrl}</p>
}为确保环境变量在运行时读取(而非在构建时打包),请在从 process.env 读取之前使用 connection() 函数:
¥To ensure environment variables are read at runtime (not bundled at build time), use the connection() function before reading from process.env:
tsx
import { connection } from 'next/server'
export default async function Page() {
await connection()
const config = process.env.RUNTIME_CONFIG
return <p>{config}</p>
}了解有关 环境变量 的更多信息。
¥Learn more about environment variables.
devIndicators 选项
¥devIndicators Options
以下选项已从 devIndicators 中移除:
¥The following options have been removed from devIndicators:
appIsrStatusbuildActivitybuildActivityPosition
指示器本身仍然可用。
¥The indicator itself remains available.
experimental.dynamicIO
experimental.dynamicIO 标志已重命名为 cacheComponents:
¥The experimental.dynamicIO flag has been renamed to cacheComponents:
更新 Next.js 配置文件,移除 dynamicIO 标志。
¥Update your Next config file, by removing the dynamicIO flag.
将 cacheComponents 标志设置为 true。
¥Add the cacheComponents flag set to true.
unstable_rootParams
unstable_rootParams 函数已被移除。我们正在开发一个替代 API,将在即将发布的次要版本中推出。
¥The unstable_rootParams function has been removed. We are working on an alternative API that we will ship in an upcoming minor release.