Codemods
Codemodsは、コードベースに対してプログラム的に実行される変換です。これにより、大量の変更を手動で各ファイルを確認することなくプログラム的に適用できます。
Next.jsは、APIが更新または非推奨になった際にNext.jsコードベースをアップグレードするためのCodemod変換を提供しています。
使用方法
ターミナルでプロジェクトフォルダに移動(cd)した後、以下を実行します:
npx @next/codemod <transform> <path><transform>と<path>を適切な値に置き換えてください。
transform- 変換名path- 変換対象のファイルまたはディレクトリ--dryドライランを実行(コードは編集されません)--print変更後の出力を比較用に表示
Codemods一覧
15.0
App RouterのRoute Segment Config runtime値をexperimental-edgeからedgeに変換
app-dir-runtime-config-experimental-edge
注記: このCodemodはApp Router専用です。
npx @next/codemod@latest app-dir-runtime-config-experimental-edge .このCodemodはRoute Segment Config 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 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 .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-nextCreate 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 transformが動作するように、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-configwithAmp 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__ディレクトリで確認できます。