Codemods
Codemods 是以程式化方式在你的程式碼庫上執行的轉換。這允許程式化地套用大量變更,而無需手動瀏覽每個檔案。
Next.js 提供 Codemod 轉換,以協助你在 API 更新或棄用時升級你的 Next.js 程式碼庫。
用法
在你的終端機中,導航 (cd
) 進入你的專案資料夾,然後執行
npx @next/codemod <transform> <path>
將 <transform>
和 <path>
替換為適當的值。
transform
- 轉換的名稱path
- 要轉換的檔案或目錄--dry
執行預演,不會編輯任何程式碼--print
列印變更後的輸出以進行比較
Codemods
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 將 路由區段設定 runtime
值 experimental-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 (來自 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
來解包 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 將 動態 OG 圖片產生的 ImageResponse
導入從 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 metadata 遷移到 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
。
例如
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
,透過新增內聯樣式並移除未使用的 props。
- 移除
layout
prop 並新增style
。 - 移除
objectFit
prop 並新增style
。 - 移除
objectPosition
prop 並新增style
。 - 移除
lazyBoundary
prop。 - 移除
lazyRoot
prop。
從 Link 元件中移除 <a> 標籤
new-link
npx @next/codemod@latest new-link .
移除 Link 元件內部的 <a>
標籤,或為無法自動修復的 Link 新增 legacyBehavior
prop。
例如
<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
prop。這允許你的應用程式繼續使用該特定連結的舊行為。
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 特定功能。
請在此討論中分享任何與此轉換相關的意見回饋in this discussion。
10
新增 React 導入
add-missing-react-import
npx @next/codemod add-missing-react-import
轉換未導入 React
的檔案以包含導入,以便新的 React JSX 轉換 能夠運作。
例如
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 及更高版本。
將匿名元件轉換為具名元件,以確保它們與 快速重新整理 一起運作。
例如
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-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.dev.org.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__
目錄中找到。
這有幫助嗎?