コンテンツをスキップ

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.jslayout.jsroute.js、またはdefault.js)またはgenerateMetadata/generateViewport APIでparamsまたはsearchParamsプロパティへのアクセスを検出した場合、呼び出し元を同期関数から非同期関数に変換し、プロパティアクセスを待機しようとします。非同期にできない場合(クライアントコンポーネントなど)、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が接頭辞として付与されます。これらのコメントが明示的に削除されるまで、ビルドはエラーになります。詳細を読む

NextRequestgeoおよびipプロパティを@vercel/functionsに置き換える

next-request-geo-ip
ターミナル
npx @next/codemod@latest next-request-geo-ip .

このcodemodは@vercel/functionsをインストールし、NextRequestgeoおよび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/imagenext/imageに名前変更します。

例:

pages/index.js
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>
  )
}

以下に変換されます。

pages/index.js
// '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>
  )
}

新しいImageコンポーネントへの移行

next-image-experimental
ターミナル
npx @next/codemod@latest next-image-experimental .

インラインスタイルを追加し、未使用のプロパティを削除することで、next/legacy/imageから新しいnext/imageに危険な移行を行います。

  • layoutプロパティを削除し、styleを追加します。
  • objectFitプロパティを削除し、styleを追加します。
  • objectPositionプロパティを削除し、styleを追加します。
  • lazyBoundaryプロパティを削除します。
  • lazyRootプロパティを削除します。
ターミナル
npx @next/codemod@latest new-link .

Linkコンポーネント内の<a>タグを削除するか、自動修正できないリンクにlegacyBehaviorプロパティを追加します。

例:

<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>

自動修正が適用できない場合、legacyBehaviorプロパティが追加されます。これにより、アプリケーションはその特定のリンクに対して古い動作を維持できます。

const Component = () => <a>About</a>
 
<Link href="/about">
  <Component />
</Link>
// becomes
<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をインポートしないファイルを変換して、新しいReact JSXトランスフォームが動作するようにします。

例:

my-component.js
export default class Home extends React.Component {
  render() {
    return <div>Hello World</div>
  }
}

以下に変換されます。

my-component.js
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で動作するようにします。

例:

my-component.js
export default function () {
  return <div>Hello World</div>
}

以下に変換されます。

my-component.js
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のページ設定に変換します。

例:

// 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,
}

6

withRouterの使用

url-to-withrouter
ターミナル
npx @next/codemod url-to-withrouter

トップレベルページに自動的に注入されていた非推奨のurlプロパティを、withRouterとそれが注入するrouterプロパティを使用するように変換します。詳細はこちらをご覧ください: https://nextjs.dokyumento.jp/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__ディレクトリで見つけることができます。