Codemods 是在您的代码库上以编程方式运行的转换。这允许以编程方式应用大量更改,而无需手动遍历每个文件。
Next.js 提供 Codemod 转换,以帮助您在 API 更新或弃用时升级您的 Next.js 代码库。
在您的终端中,导航 (cd) 到您的项目文件夹,然后运行:
npx @next/codemod <transform> <path>将 <transform> 和 <path> 替换为适当的值。
transform - 转换的名称path - 要转换的文件或目录--dry 执行空运行,不会修改任何代码--print 打印更改后的输出以进行比较experimental_ppr 路由段配置remove-experimental-pprnpx @next/codemod@latest remove-experimental-ppr .此 codemod 从 App Router 页面和布局中移除 experimental_ppr 路由段配置。
- export const experimental_ppr = true;unstable_ 前缀remove-unstable-prefixnpx @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 约定迁移到 proxymiddleware-to-proxynpx @next/codemod@latest middleware-to-proxy .此 codemod 将项目从使用已弃用的 middleware 约定迁移到使用 proxy 约定。它会:
middleware.<extension> 重命名为 proxy.<extension> (例如,middleware.ts 重命名为 proxy.ts)middleware 重命名为 proxyexperimental.middlewarePrefetch 重命名为 experimental.proxyPrefetchexperimental.middlewareClientMaxBodySize 重命名为 experimental.proxyClientMaxBodySizeexperimental.externalMiddlewareRewritesResolve 重命名为 experimental.externalProxyRewritesResolveskipMiddlewareUrlNormalize 重命名为 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 CLInext-lint-to-eslint-clinpx @next/codemod@canary next-lint-to-eslint-cli .此 codemod 将项目从使用 next lint 迁移到使用 ESLint CLI 和您的本地 ESLint 配置。它会:
eslint.config.mjs 文件package.json 脚本以使用 eslint . 而非 next lintpackage.json例如:
{
"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 eslintConfigruntime 值从 experimental-edge 转换为 edgeapp-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'以前支持同步访问并选择动态渲染的 API 现在是异步的。您可以在升级指南中阅读有关此重大更改的更多信息。
next-async-request-apinpx @next/codemod@latest next-async-request-api .此 codemod 会将现在已变为异步的动态 API(来自 next/headers 的 cookies()、headers() 和 draftMode())转换为正确 await 或在适用时使用 React.use() 包装。
当无法进行自动迁移时,codemod 会添加一个类型转换(如果是 TypeScript 文件)或一个注释,以告知用户需要手动审查和更新。
例如:
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 = (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 (headers() as unknown as UnsafeUnwrappedHeaders).get('x-foo')
}当我们检测到页面/路由入口(page.js、layout.js、route.js 或 default.js)中的 params 或 searchParams 属性,或者 generateMetadata / generateViewport API 上的属性访问时,
它将尝试将调用点从同步函数转换为异步函数,并 await 属性访问。如果无法使其变为异步(例如对于客户端组件),它将使用 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/functionsnext-request-geo-ipnpx @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)
}ImageResponse 导入next-og-importnpx @next/codemod@latest next-og-import .此 codemod 将 next/server 的导入转换为 next/og,以便使用动态开放图图像生成。
例如:
import { ImageResponse } from 'next/server'转换为:
import { ImageResponse } from 'next/og'viewport 导出metadata-to-viewport-exportnpx @next/codemod@latest metadata-to-viewport-export .此 codemod 会将某些视口元数据迁移到 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',
}built-in-next-fontnpx @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'next-image-to-legacy-imagenpx @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' becomes 'next/legacy/image'
import Image1 from 'next/legacy/image'
// 'next/future/image' becomes '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>
)
}next-image-experimentalnpx @next/codemod@latest next-image-experimental .危险地将 next/legacy/image 迁移到新的 next/image,通过添加内联样式和移除未使用的 props。
layout prop 并添加 style。objectFit prop 并添加 style。objectPosition prop 并添加 style。lazyBoundary prop。lazyRoot prop。<a> 标签new-linknpx @next/codemod@latest new-link .移除 <Link> 组件内部的 <a> 标签。
移除 <Link> 组件内部的 <a> 标签。
例如:
<Link href="/about">
<a>About</a>
</Link>
// transforms into
<Link href="/about">
About
</Link>
<Link href="/about">
<a onClick={() => console.log('clicked')}>About</a>
</Link>
// transforms into
<Link href="/about" onClick={() => console.log('clicked')}>
About
</Link>cra-to-nextnpx @next/codemod cra-to-next将 Create React App 项目迁移到 Next.js;创建 Pages Router 和必要的配置以匹配行为。最初利用仅客户端渲染来防止因 SSR 期间 window 的使用而破坏兼容性,并且可以无缝启用,以允许逐步采用 Next.js 特性。
请在此讨论中分享与此转换相关的任何反馈。
add-missing-react-importnpx @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>
}
}name-default-componentnpx @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>
}该组件将根据文件名拥有一个驼峰式命名的名称,它也适用于箭头函数。
注意:内置的 AMP 支持和此 codemod 已在 Next.js 16 中移除。
withamp-to-confignpx @next/codemod withamp-to-config将 withAmp HOC 转换为 Next.js 9 页面配置。
例如:
// Before
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export default withAmp(Home)// After
export default function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
amp: true,
}withRouterurl-to-withrouternpx @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__ 目录中找到。