Codemods
使用 codemods 在新功能发布时升级你的 Next.js 代码库。
Codemods 是以编程方式在代码库上运行的转换。这使得大量更改能够以编程方式应用,而无需手动逐个检查每个文件。
当 API 更新或弃用时,Next.js 提供 Codemod 转换来帮助升级你的 Next.js 代码库。
用法#
在终端中,使用 (cd) 进入项目文件夹,然后运行:
npx @next/codemod <transform> <path>将 <transform> 和 <path> 替换为适当的值。
transform- 转换名称path- 要转换的文件或目录--dry执行试运行,不会编辑任何代码--print打印更改后的输出以供比较
升级#
升级你的 Next.js 应用程序,自动运行 codemods 并更新 Next.js、React 和 React DOM。
要让编码代理运行 codemods、完成剩余的迁移工作并验证应用,请改为运行 npx next@canary upgrade --agent=latest。详情请参阅使用编码代理升级。
npx @next/codemod upgrade [revision]选项#
revision(可选):指定升级类型(patch、minor、major)、NPM 发布标签(例如latest、canary、rc)或精确版本(例如15.0.0)。稳定版本默认为minor。--verbose:在升级过程中显示更详细的输出。--skip-react-upgrade:保留 React 依赖项、类型和 overrides,并跳过 React codemods。--skip-eslint-upgrade:保留eslint、eslint-config-next、@next/eslint-plugin-next,并跳过next-lint-to-eslint-cli。在验证前手动完成所需的 lint 迁移。-y, --yes:跳过所有交互式提示并接受其默认值(将 React 升级到 18 以上、启用 Turbopack、应用所有推荐的 codemods、运行 React 19 codemods)。当 stdin 不是 TTY 时(CI、AI 编码代理或任何非交互式 shell)也会自动启用,因此通常无需显式传入。
例如:
# 升级到最新的补丁版本(例如 16.0.7 -> 16.0.8)
npx @next/codemod upgrade patch
# 升级到最新的次版本(例如 15.3.7 -> 15.4.8)。这是默认选项。
npx @next/codemod upgrade minor
# 升级到最新的主版本(例如 15.5.7 -> 16.0.7)
npx @next/codemod upgrade major
# 升级到特定版本
npx @next/codemod upgrade 16
# 升级到 canary 版本
npx @next/codemod upgrade canary
# 从代理或 CI 运行:跳过所有提示
npx @next/codemod upgrade canary --yes小知识:
- 如果目标版本与当前版本相同或更低,命令将退出且不进行任何更改。
- 跳过标志不会绕过目标版本的 peer dependency 要求。如果之前安装失败,请修复依赖项并使用相关标志重试完全相同的目标版本。如果 Next.js 已与目标版本匹配,请使用下面的指南单独运行任何跳过的迁移。
- 在升级过程中,系统可能会提示你选择要应用的 Next.js codemods,并在升级 React 时运行 React 19 codemods。
- 当由 AI 编码代理调用或在 CI 中调用时(任何 stdin 不是 TTY 的地方),升级将以非交互方式运行并接受所有默认值。即使从终端运行,也可以传入
--yes来强制此行为。
Codemods#
16.3#
让每条路由都退出 Cache Components 验证#
cache-components-instant-false#
npx @next/codemod@canary cache-components-instant-false ./app此 codemod 会向 app 目录中尚未导出 instant 的每个 {page,layout,default} 文件添加 export const instant = false,以便你启用 cacheComponents,然后逐条路由移除退出项。它会跳过 Client Components("use client")和已声明 instant 的文件。生成的 @next-codemod-ignore 注释会标记这一有意的退出,而不会阻塞编译。
小知识:在
src/项目中传入./src/app。路径错误会报告0 ok而不是失败,因此请检查文件数量。
+ // @next-codemod-ignore 采用 Cache Components:此片段临时允许阻塞。
+ // 在验证此片段无需退出即可通过验证后,移除此退出项。
+ // 请参阅:https://nextjs.org/docs/app/guides/migrating-to-cache-components
+ export const instant = false
+
export default function Page() {
return <h1>Hello</h1>
}有关完整的采用路径,请参阅迁移到 Cache Components指南。
启用 Partial Prefetching 后移除 prefetch = 'partial' 路由片段配置#
remove-partial-prefetch#
npx @next/codemod@canary remove-partial-prefetch ./app此 codemod 会从 app 目录中的 {page,layout} 文件移除 export const prefetch = 'partial',以便你全局启用 partialPrefetching,然后删除现在已冗余的逐路由选择加入项。它只移除 'partial' 值,并保留其他值,例如 prefetch = 'force-disabled'。
小知识:在
src/项目中传入./src/app。路径错误会报告0 ok而不是失败,因此请检查文件数量。
- export const prefetch = 'partial'有关完整的采用路径,请参阅采用 Partial Prefetching指南。
16.0#
从 App Router 页面和布局中移除 experimental_ppr 路由片段配置#
remove-experimental-ppr#
npx @next/codemod@latest remove-experimental-ppr .此 codemod 会从 App Router 页面和布局中移除 experimental_ppr 路由片段配置。
- export const experimental_ppr = true;从已稳定的 API 中移除 unstable_ 前缀#
remove-unstable-prefix#
npx @next/codemod@latest remove-unstable-prefix .此 codemod 会从已稳定的 API 中移除 unstable_ 前缀。
例如:
import { unstable_cacheTag as cacheTag } from 'next/cache'
cacheTag()转换为:
import { cacheTag } from 'next/cache'
cacheTag()从已弃用的 middleware 约定迁移到 proxy#
middleware-to-proxy#
npx @next/codemod@latest middleware-to-proxy .此 codemod 将项目从使用已弃用的 middleware 约定迁移到使用 proxy 约定。它会:
- 将
middleware.<extension>重命名为proxy.<extension>(例如将middleware.ts重命名为proxy.ts) - 将具名导出
middleware重命名为proxy - 将 Next.js 配置属性
experimental.middlewarePrefetch重命名为experimental.proxyPrefetch - 将 Next.js 配置属性
experimental.middlewareClientMaxBodySize重命名为experimental.proxyClientMaxBodySize - 将 Next.js 配置属性
experimental.externalMiddlewareRewritesResolve重命名为experimental.externalProxyRewritesResolve - 将 Next.js 配置属性
skipMiddlewareUrlNormalize重命名为skipProxyUrlNormalize
例如:
import { NextResponse } from 'next/server'
export function middleware() {
return NextResponse.next()
}转换为:
import { NextResponse } from 'next/server'
export function proxy() {
return NextResponse.next()
}从 next lint 迁移到 ESLint CLI#
next-lint-to-eslint-cli#
npx @next/codemod@canary next-lint-to-eslint-cli .此 codemod 将项目从使用 next lint 迁移到使用 ESLint CLI 和你本地的 ESLint 配置。它会:
- 创建一个包含 Next.js 推荐配置的
eslint.config.mjs文件 - 更新
package.json脚本,使用eslint .代替next lint - 向
package.json添加必要的 ESLint 依赖项 - 找到现有 ESLint 配置时予以保留
例如:
{
"scripts": {
"lint": "next lint"
}
}变为:
{
"scripts": {
"lint": "eslint ."
}
}并创建:
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { FlatCompat } from '@eslint/eslintrc'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const compat = new FlatCompat({
baseDirectory: __dirname,
})
const eslintConfig = [
...compat.extends('next/core-web-vitals', 'next/typescript'),
{
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
},
]
export default eslintConfig15.0#
将 App Router 路由片段配置 runtime 的值从 experimental-edge 转换为 edge#
app-dir-runtime-config-experimental-edge#
注意:此 codemod 特定于 App Router。
npx @next/codemod@latest app-dir-runtime-config-experimental-edge .此 codemod 将路由片段配置 runtime的值 experimental-edge 转换为 edge。
例如:
export const runtime = 'experimental-edge'转换为:
export const runtime = 'edge'迁移到异步 Dynamic API#
之前支持同步访问的选择加入动态渲染的 API 现在是异步的。你可以在升级指南中阅读有关此破坏性更改的更多信息。
next-async-request-api#
npx @next/codemod@latest next-async-request-api .此 codemod 会将现在为异步的动态 API(next/headers 中的 cookies()、headers() 和 draftMode())转换为正确 await 的形式,或在适用时使用 React.use() 包裹。 当无法自动迁移时,codemod 会添加一条 @next-codemod-error 注释,并可能添加一个临时的 UnsafeUnwrapped* 类型转换。在移除它们之前请完成迁移。如果建议的更改不适用,请将该指令替换为 @next-codemod-ignore 并说明原因。
有关示例,请参阅异步请求 API 迁移指南。
例如:
import { cookies, headers } from 'next/headers'
const token = cookies().get('token')
function useToken() {
const token = cookies().get('token')
return token
}
export default function Page() {
const name = cookies().get('name')
}
function getHeader() {
return headers().get('x-foo')
}转换为:
import { use } from 'react'
import {
cookies,
headers,
type UnsafeUnwrappedCookies,
type UnsafeUnwrappedHeaders,
} from 'next/headers'
const token =
/* @next-codemod-error 等待此 API 并更新其调用方;修复迁移后移除临时的 UnsafeUnwrappedCookies 类型转换。 */
(cookies() as unknown as UnsafeUnwrappedCookies).get('token')
function useToken() {
const token = use(cookies()).get('token')
return token
}
export default async function Page() {
const name = (await cookies()).get('name')
}
function getHeader() {
return (
/* @next-codemod-error 等待此 API 并更新其调用方;修复迁移后移除临时的 UnsafeUnwrappedHeaders 类型转换。 */
(headers() as unknown as UnsafeUnwrappedHeaders).get('x-foo')
)
}当我们检测到页面/路由入口(page.js、layout.js、route.js 或 default.js)中 params 或 searchParams props 的属性访问,或 generateMetadata / generateViewport API 中的属性访问时,它会尝试将调用点从同步函数转换为异步函数,并 await 该属性访问。如果无法设为异步(例如 Client Component),它将使用 React.use 来解包 promise。
例如:
// page.tsx
export default function Page({
params,
searchParams,
}: {
params: { slug: string }
searchParams: { [key: string]: string | string[] | undefined }
}) {
const { value } = searchParams
if (value === 'foo') {
// ...
}
}
export function generateMetadata({ params }: { params: { slug: string } }) {
const { slug } = params
return {
title: `My Page - ${slug}`,
}
}转换为:
// page.tsx
export default async function Page(props: {
params: Promise<{ slug: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
const searchParams = await props.searchParams
const { value } = searchParams
if (value === 'foo') {
// ...
}
}
export async function generateMetadata(props: {
params: Promise<{ slug: string }>
}) {
const params = await props.params
const { slug } = params
return {
title: `My Page - ${slug}`,
}
}小知识: 当此 codemod 识别出可能需要手动干预但无法确定确切修复方案的位置时,它会在代码中添加一条注释或类型转换,以告知用户需要手动更新。这些注释以 @next/codemod 为前缀,类型转换以
UnsafeUnwrapped为前缀。 在这些注释被明确移除之前,你的构建会报错。了解更多。
将 NextRequest 的 geo 和 ip 属性替换为 @vercel/functions#
next-request-geo-ip#
npx @next/codemod@latest next-request-geo-ip .此 codemod 会安装 @vercel/functions,并将 NextRequest 的 geo 和 ip 属性转换为相应的 @vercel/functions 功能。
例如:
import type { NextRequest } from 'next/server'
export function GET(req: NextRequest) {
const { geo, ip } = req
}转换为:
import type { NextRequest } from 'next/server'
import { geolocation, ipAddress } from '@vercel/functions'
export function GET(req: NextRequest) {
const geo = geolocation(req)
const ip = ipAddress(req)
}14.0#
迁移 ImageResponse 导入#
next-og-import#
npx @next/codemod@latest next-og-import .此 codemod 将用于动态 OG 图片生成的导入从 next/server 转换为 next/og。
例如:
import { ImageResponse } from 'next/server'转换为:
import { ImageResponse } from 'next/og'使用 viewport 导出#
metadata-to-viewport-export#
npx @next/codemod@latest metadata-to-viewport-export .此 codemod 将某些 viewport 元数据迁移到 viewport 导出。
例如:
export const metadata = {
title: 'My App',
themeColor: 'dark',
viewport: {
width: 1,
},
}转换为:
export const metadata = {
title: 'My App',
}
export const viewport = {
width: 1,
themeColor: 'dark',
}13.2#
使用内置字体#
built-in-next-font#
npx @next/codemod@latest built-in-next-font .此 codemod 会卸载 @next/font 包,并将 @next/font 导入转换为内置的 next/font。
例如:
import { Inter } from '@next/font/google'转换为:
import { Inter } from 'next/font/google'13.0#
重命名 Next Image 导入#
next-image-to-legacy-image#
npx @next/codemod@latest next-image-to-legacy-image .将现有 Next.js 10、11 或 12 应用程序中的 next/image 导入安全地重命名为 Next.js 13 中的 next/legacy/image。同时也会将 next/future/image 重命名为 next/image。
例如:
import Image1 from 'next/image'
import Image2 from 'next/future/image'
export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}转换为:
// 'next/image' 变为 'next/legacy/image'
import Image1 from 'next/legacy/image'
// 'next/future/image' 变为 'next/image'
import Image2 from 'next/image'
export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}迁移到新的 Image 组件#
next-image-experimental#
npx @next/codemod@latest next-image-experimental .通过添加内联样式并移除未使用的 props,以有风险的方式从 next/legacy/image 迁移到新的 next/image。
- 移除
layoutprop 并添加style。 - 移除
objectFitprop 并添加style。 - 移除
objectPositionprop 并添加style。 - 移除
lazyBoundaryprop。 - 移除
lazyRootprop。
从 Link 组件中移除 <a> 标签#
new-link#
npx @next/codemod@latest new-link .移除 Link 组件内部的 <a> 标签。
移除 Link 组件内部的 <a> 标签。
例如:
<Link href="/about">
<a>About</a>
</Link>
// 转换为
<Link href="/about">
About
</Link>
<Link href="/about">
<a onClick={() => console.log('clicked')}>About</a>
</Link>
// 转换为
<Link href="/about" onClick={() => console.log('clicked')}>
About
</Link>11#
从 CRA 迁移#
cra-to-next#
npx @next/codemod cra-to-next将 Create React App 项目迁移到 Next.js;创建一个 Pages Router 和必要的配置以匹配原有行为。最初会利用仅限客户端的渲染,以防止因 SSR 期间使用 window 而破坏兼容性,并且可以无缝启用,以逐步采用 Next.js 特有的功能。
请在此讨论中分享与此转换相关的任何反馈。
10#
添加 React 导入#
add-missing-react-import#
npx @next/codemod add-missing-react-import转换未导入 React 的文件,使其包含该导入,以便新的 React JSX 转换能够工作。
例如:
export default class Home extends React.Component {
render() {
return <div>Hello World</div>
}
}转换为:
import React from 'react'
export default class Home extends React.Component {
render() {
return <div>Hello World</div>
}
}9#
将匿名组件转换为具名组件#
name-default-component#
npx @next/codemod name-default-component版本 9 及以上。
将匿名组件转换为具名组件,以确保它们能与 Fast Refresh 一起工作。
例如:
export default function () {
return <div>Hello World</div>
}转换为:
export default function MyComponent() {
return <div>Hello World</div>
}该组件将具有基于文件名的驼峰式名称,并且也适用于箭头函数。
8#
注意:内置 AMP 支持和此 codemod 已在 Next.js 16 中移除。
将 AMP HOC 转换为页面配置#
withamp-to-config#
npx @next/codemod withamp-to-config将 withAmp HOC 转换为 Next.js 9 页面配置。
例如:
// 之前
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export default withAmp(Home)// 之后
export default function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
amp: true,
}6#
使用 withRouter#
url-to-withrouter#
npx @next/codemod url-to-withrouter将顶级页面上已弃用的自动注入的 url 属性转换为使用 withRouter 及其注入的 router 属性。在此处阅读更多信息:https://nextjs.org/docs/messages/url-deprecated
例如:
import React from 'react'
export default class extends React.Component {
render() {
const { pathname } = this.props.url
return <div>Current pathname: {pathname}</div>
}
}import React from 'react'
import { withRouter } from 'next/router'
export default withRouter(
class extends React.Component {
render() {
const { pathname } = this.props.router
return <div>Current pathname: {pathname}</div>
}
}
)这只是一种情况。所有被转换(并经过测试)的情况都可以在__testfixtures__ 目录中找到。