跳到內容
指南升級Codemods

程式碼修改器

Codemods 是以程式設計方式在程式碼庫上執行的轉換。這允許以程式設計方式應用大量更改,而無需手動逐個檔案進行操作。

當 API 更新或棄用時,Next.js 提供 Codemod 轉換以幫助升級您的 Next.js 程式碼庫。

用法

在您的終端中,導航 (cd) 到您的專案資料夾,然後執行

終端
npx @next/codemod <transform> <path>

<transform><path> 替換為適當的值。

  • transform - 轉換名稱
  • path - 要轉換的檔案或目錄
  • --dry 執行空執行,不會編輯任何程式碼
  • --print 列印更改後的輸出以供比較

碼轉換

16.0

從 App Router 頁面和佈局中刪除 experimental_ppr 路由段配置

remove-experimental-ppr
終端
npx @next/codemod@latest remove-experimental-ppr .

此 codemod 從 App Router 頁面和佈局中刪除 experimental_ppr 路由段配置。

app/page.tsx
- 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
  • 將 Next.js 配置屬性 skipMiddlewareUrlNormalize 重新命名為 skipProxyUrlNormalize

例如

middleware.ts
import { NextResponse } from 'next/server'
 
export function middleware() {
  return NextResponse.next()
}

轉換為

proxy.ts
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 CLI 和您的本地 ESLint 配置。它會

  • 建立一個包含 Next.js 推薦配置的 eslint.config.mjs 檔案
  • 更新 package.json 指令碼以使用 eslint . 而不是 next lint
  • package.json 新增必要的 ESLint 依賴項
  • 保留現有 ESLint 配置(如果找到)

例如

package.json
{
  "scripts": {
    "lint": "next lint"
  }
}

變成

package.json
{
  "scripts": {
    "lint": "eslint ."
  }
}

並建立

eslint.config.mjs
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 eslintConfig

15.0

將 App Router 路由段配置 runtime 值從 experimental-edge 轉換為 edge

app-dir-runtime-config-experimental-edge

注意:此 codemod 僅適用於 App Router。

終端
npx @next/codemod@latest app-dir-runtime-config-experimental-edge .

此 codemod 將 路由段配置 runtimeexperimental-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 .

此 codemod 將現在已非同步的動態 API(cookies()headers()draftMode() 來自 next/headers)轉換為適當地等待,或在適用時使用 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.jsdefault.js) 或 generateMetadata / generateViewport API 中的 paramssearchParams 屬性上的屬性訪問時,它將嘗試將呼叫點從同步函式轉換為非同步函式,並等待屬性訪問。如果無法使其變為非同步 (例如客戶端元件),它將使用 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 為字首。在明確刪除這些註釋之前,您的構建將出錯。閱讀更多

NextRequestgeoip 屬性替換為 @vercel/functions

next-request-geo-ip
終端
npx @next/codemod@latest next-request-geo-ip .

此 codemod 安裝 @vercel/functions 並將 NextRequestgeoip 屬性轉換為相應的 @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 匯出。

例如

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 13 中,安全地將現有 Next.js 10、11 或 12 應用程式中的 next/image 匯入重新命名為 next/legacy/image。同時將 next/future/image 重新命名為 next/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 .

透過新增內聯樣式和刪除未使用的 prop,危險地從 next/legacy/image 遷移到新的 next/image

  • 刪除 layout prop 並新增 style
  • 刪除 objectFit prop 並新增 style
  • 刪除 objectPosition prop 並新增 style
  • 刪除 lazyBoundary prop。
  • 刪除 lazyRoot prop。
終端
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-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 及以上。

將匿名元件轉換為命名元件,以確保它們與快速重新整理一起工作。

例如

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

轉換為

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

元件將具有基於檔名的駝峰式命名,並且它也適用於箭頭函式。

8

注意:Next.js 16 中已刪除內建 AMP 支援和此 codemod。

將 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.react.com.tw/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__ 目錄中找到。