コードモッド
コードモッドは、コードベースにプログラム的に実行される変換です。これにより、すべてのファイルを手動で確認することなく、多数の変更をプログラム的に適用することができます。
Next.jsは、APIが更新または非推奨になったときにNext.jsコードベースのアップグレードを支援するためのコードモッド変換を提供しています。
使用方法
ターミナルで、プロジェクトのフォルダに移動(cd
)し、以下を実行します:
npx @next/codemod <transform> <path>
<transform>
と<path>
を適切な値に置き換えてください。
transform
- 変換の名前path
- 変換するファイルまたはディレクトリ--dry
ドライランを実行し、コードは編集されません--print
比較のために変更された出力を表示します
コードモッド
15.0
App Routerのルートセグメント設定のruntime
値をexperimental-edge
からedge
に変換
app-dir-runtime-config-experimental-edge
注意: このコードモッドはApp Router専用です。
npx @next/codemod@latest app-dir-runtime-config-experimental-edge .
このコードモッドはルートセグメント設定のruntime
値experimental-edge
をedge
に変換します。
例:
export const runtime = 'experimental-edge'
以下のように変換されます:
export const runtime = 'edge'
非同期動的APIへの移行
動的レンダリングを利用し、以前は同期アクセスをサポートしていたAPIが現在は非同期になっています。この破壊的変更の詳細については、アップグレードガイドを参照してください。
next-async-request-api
npx @next/codemod@latest next-async-request-api .
このコードモッドは、現在非同期になった動的API(next/headers
からのcookies()
、headers()
、draftMode()
)を適切にawait
または該当する場合はReact.use()
でラップするように変換します。
自動的な移行が不可能な場合、コードモッドは(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')
}
params
または searchParams
プロップに対するプロパティアクセスをページ/ルートエントリ(page.js
、layout.js
、route.js
、または default.js
)または generateMetadata
/ generateViewport
APIで検出すると、コールサイトを同期関数から非同期関数に変換し、プロパティアクセスを 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}`,
}
}
補足: このコードモッドが手動の介入が必要な箇所を特定したが、正確な修正方法を判断できない場合、ユーザーがマニュアルで更新する必要があることを知らせるためにコードにコメントや型キャストを追加します。これらのコメントには**@next/codemod**というプレフィックスが付けられ、型キャストには
UnsafeUnwrapped
というプレフィックスが付けられます。 これらのコメントが明示的に削除されるまで、ビルドはエラーになります。詳細
NextRequest
のgeo
およびip
プロパティを@vercel/functions
に置き換える
next-request-geo-ip
npx @next/codemod@latest next-request-geo-ip .
このコードモッドは@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 .
このコードモッドは、動的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 .
このコードモッドは特定のビューポートメタデータを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 .
このコードモッドは@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>
)
}
新しい画像コンポーネントへの移行
next-image-experimental
npx @next/codemod@latest next-image-experimental .
インラインスタイルを追加し、未使用のpropsを削除することで、next/legacy/image
から新しいnext/image
に危険なく移行します。
layout
propを削除し、style
を追加します。objectFit
propを削除し、style
を追加します。objectPosition
propを削除し、style
を追加します。lazyBoundary
propを削除します。lazyRoot
propを削除します。
Linkコンポーネントから<a>
タグを削除
new-link
npx @next/codemod@latest new-link .
Linkコンポーネント内の<a>
タグを削除するか、自動修正できないLinkにlegacyBehavior
propを追加します。
例:
<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
propが追加されます。これにより、アプリケーションはその特定のリンクについて古い動作を使用し続けることができます。
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__
ディレクトリにあります。