コードモッド
Codemodsはコードベースにプログラム的に実行される変換です。これにより、すべてのファイルを手動で確認することなく、多数の変更をプログラム的に適用することができます。
Next.jsは、APIが更新または非推奨になった場合にNext.jsのコードベースをアップグレードするためのCodemod変換を提供しています。
使用方法
ターミナルで、プロジェクトのフォルダに移動(cd
)し、次のコマンドを実行します:
npx @next/codemod <transform> <path>
<transform>
と<path>
を適切な値に置き換えます。
transform
- 変換の名前path
- 変換するファイルまたはディレクトリ--dry
ドライランを実行し、コードは編集されません--print
比較のために変更された出力を表示します
Codemods
15.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は(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
)またはgenerateMetadata
/generateViewport
APIでparams
またはsearchParams
プロップのプロパティアクセスを検出した場合、
コールサイトを同期から非同期関数に変換し、プロパティアクセスをawaitしようとします。(クライアントコンポーネントなどで)非同期にできない場合は、プロミスをアンラップするためにReact.use
を使用します。
例:
// 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
エクスポートに移行します。
例:
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 13で、既存のNext.js 10、11、または12アプリケーションのnext/image
インポートを安全に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 .
インラインスタイルを追加し、未使用のプロップを削除することで、next/legacy/image
から新しいnext/image
への危険な移行を行います。
layout
プロップを削除し、style
を追加します。objectFit
プロップを削除し、style
を追加します。objectPosition
プロップを削除し、style
を追加します。lazyBoundary
プロップを削除します。lazyRoot
プロップを削除します。
Linkコンポーネントから<a>
タグを削除する
new-link
npx @next/codemod@latest new-link .
Linkコンポーネント内の<a>
タグを削除するか、自動修正できないLinkにlegacyBehavior
プロップを追加します。
例:
<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>
自動修正が適用できない場合、legacyBehavior
プロップが追加されます。これにより、アプリケーションはその特定のリンクに対して古い動作を使用して機能し続けることができます。
const Component = () => <a>About</a>
<Link href="/about">
<Component />
</Link>
// 次のようになります
<Link href="/about" legacyBehavior>
<Component />
</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 JSX変換が機能するように、React
をインポートしていないファイルを変換してインポートを含めます。
例:
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 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__
ディレクトリにあります。