コンテンツにスキップ

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

注意: このコードモッドは App Router 専用です。

ターミナル
npx @next/codemod@latest app-dir-runtime-config-experimental-edge .

このコードモッドは、Route Segment Config の runtime の値 experimental-edgeedge に変換します。

例:

export const runtime = 'experimental-edge'

変換後:

export const runtime = 'edge'

非同期 Dynamic API への移行

以前は同期アクセスをサポートしていた動的レンダリングを選択した API は、現在非同期です。この破壊的変更の詳細については、アップグレードガイドを参照してください。

next-async-request-api
ターミナル
npx @next/codemod@latest next-async-request-api .

このコードモッドは、現在非同期である動的API(cookies()headers()draftMode() from next/headers)を、該当する場合は適切に 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')
}

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

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

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

このコードモッドは @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 .

このコードモッドは、動的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 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 JSX transformが機能するために、React をインポートしていないファイルをインポートを含むように変換します。

例:

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__ ディレクトリで確認できます。