Codemods
Codemods は、コードベースにプログラムで適用される変換です。これにより、すべてのファイルを個別に確認することなく、多数の変更をプログラムで適用できます。
Next.js は、API の更新または非推奨化された際に、Next.js コードベースをアップグレードするための Codemod 変換を提供します。
使用方法
ターミナルで、プロジェクトのフォルダーに移動 (cd) してから、次を実行します。
npx @next/codemod <transform> <path><transform> と <path> を適切な値に置き換えます。
transform- 変換の名前path- 変換するファイルまたはディレクトリ--dryドライランを実行します。コードは編集されません。--print変更された出力を表示して比較します。
Codemods
16.0
App Router のページおよびレイアウトから experimental_ppr Route Segment Config を削除
remove-experimental-ppr
npx @next/codemod@latest remove-experimental-ppr .この codemod は、App Router のページおよびレイアウトから experimental_ppr Route Segment Config を削除します。
- export const experimental_ppr = true;安定化された API から unstable_ プレフィックスを削除
remove-unstable-prefix
npx @next/codemod@latest remove-unstable-prefix .この codemod は、安定化された API から unstable_ プレフィックスを削除します。
例:
import { unstable_cacheTag as cacheTag } from 'next/cache'
cacheTag()〜に変換
import { cacheTag } from 'next/cache'
cacheTag()非推奨の middleware 規約を proxy に移行
middleware-to-proxy
npx @next/codemod@latest middleware-to-proxy .この codemod は、非推奨の middleware 規約を使用しているプロジェクトを、proxy 規約を使用するように移行します。具体的には以下の処理を行います。
middleware.<extension>をproxy.<extension>にリネームします(例:middleware.tsからproxy.tsへ)。- 名前付きエクスポート
middlewareをproxyにリネームします。 - Next.js 設定プロパティ
experimental.middlewarePrefetchをexperimental.proxyPrefetchにリネームします。 - Next.js 設定プロパティ
experimental.middlewareClientMaxBodySizeをexperimental.proxyClientMaxBodySizeにリネームします。 - Next.js 設定プロパティ
experimental.externalMiddlewareRewritesResolveをexperimental.externalProxyRewritesResolveにリネームします。 skipMiddlewareUrlNormalizeをskipProxyUrlNormalizeにリネームします。
例:
import { NextResponse } from 'next/server'
export function middleware() {
return NextResponse.next()
}〜に変換
import { NextResponse } from 'next/server'
export function proxy() {
return NextResponse.next()
}next lint を ESLint CLI に移行
next-lint-to-eslint-cli
npx @next/codemod@canary next-lint-to-eslint-cli .この codemod は、next lint を使用しているプロジェクトを、ローカルの ESLint 設定を使用した ESLint CLI を使用するように移行します。具体的には以下の処理を行います。
- Next.js の推奨設定を含む
eslint.config.mjsファイルを作成します。 package.jsonのスクリプトをnext lintからeslint .を使用するように更新します。package.jsonに必要な ESLint 依存関係を追加します。- 既存の ESLint 設定が存在する場合は保持します。
例:
{
"scripts": {
"lint": "next lint"
}
}〜になると
{
"scripts": {
"lint": "eslint ."
}
}〜を作成
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { FlatCompat } from '@eslint/eslintrc'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const compat = new FlatCompat({
baseDirectory: __dirname,
})
const eslintConfig = [
...compat.extends('next/core-web-vitals', 'next/typescript'),
{
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
},
]
export default eslintConfig15.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 への移行
以前は同期アクセスをサポートしていた Dynamic Rendering をオプトインしていた API は、非同期になりました。この破壊的変更については、アップグレードガイドで詳細を確認できます。
next-async-request-api
npx @next/codemod@latest next-async-request-api .この codemod は、現在非同期になった Dynamic 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')
}ページ/ルートエントリ (page.js、layout.js、route.js、または default.js) の params または searchParams プロパティへのアクセスを検出すると、コールサイトを同期関数から非同期関数に変換し、プロパティアクセスを await しようとします。非同期にできない場合(クライアントコンポーネントなど)、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でプレフィックスされます。これらのコメントが明示的に削除されるまで、ビルドはエラーになります。詳細はこちら。
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 は、next/server からのインポートを next/og に移動して、動的な 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 メタデータを 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' 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プロパティを削除します。
Link コンポーネントから タグを削除
new-link
npx @next/codemod@latest new-link .Link Components 内の <a> タグを削除します。
例:
<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>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-importReact をインポートしていないファイルを変換し、新しい React JSX transform が機能するようにインポートを追加します。
例:
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 サポートとこの codemod は、Next.js 16 で削除されました。
AMP HOC をページ設定に変換
withamp-to-config
npx @next/codemod withamp-to-configwithAmp 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>
}
}
)これは 1 つのケースです。変換(およびテスト)されたすべてのケースは、__testfixtures__ ディレクトリ で確認できます。
役に立ちましたか?