TypeScript

Next.js 內建 TypeScript 支援,當您使用 create-next-app 建立新專案時,會自動安裝必要的套件並配置適當的設定。

若要將 TypeScript 添加到現有專案,請將檔案重新命名為 .ts / .tsx。執行 next devnext build 會自動安裝必要的依賴項,並添加一個包含推薦配置選項的 tsconfig.json 檔案。

小知識:如果您已經有 jsconfig.json 檔案,請將 paths 編譯器選項從舊的 jsconfig.json 複製到新的 tsconfig.json 檔案中,並刪除舊的 jsconfig.json 檔案。

範例

類型檢查 next.config.ts

您可以在 Next.js 配置中使用 TypeScript 並導入類型,方法是使用 next.config.ts

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  /* 配置選項在這裡 */
}

export default nextConfig

小知識next.config.ts 中的模組解析目前僅限於 CommonJS。這可能導致與僅支援 ESM 的套件在 next.config.ts 中載入時不相容。

當使用 next.config.js 檔案時,您可以使用 JSDoc 在 IDE 中添加一些類型檢查,如下所示:

next.config.js
// @ts-check

/** @type {import('next').NextConfig} */
const nextConfig = {
  /* 配置選項在這裡 */
}

module.exports = nextConfig

靜態生成和伺服器端渲染

對於 getStaticPropsgetStaticPathsgetServerSideProps,您可以分別使用 GetStaticPropsGetStaticPathsGetServerSideProps 類型:

pages/blog/[slug].tsx
import type { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'

export const getStaticProps = (async (context) => {
  // ...
}) satisfies GetStaticProps

export const getStaticPaths = (async () => {
  // ...
}) satisfies GetStaticPaths

export const getServerSideProps = (async (context) => {
  // ...
}) satisfies GetServerSideProps

小知識satisfies 是在 TypeScript 4.9 中添加的。我們建議升級到最新版本的 TypeScript。

使用 API 路由

以下是如何在 API 路由中使用內建類型的範例:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

您還可以標記響應數據的類型:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({ name: 'John Doe' })
}

使用自訂 App

如果您有 自訂 App,您可以使用內建類型 AppProps 並將檔案名稱更改為 ./pages/_app.tsx,如下所示:

import type { AppProps } from 'next/app'

export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

增量類型檢查

v10.2.1 起,Next.js 支援 增量類型檢查,當在您的 tsconfig.json 中啟用時,這可以幫助加速大型應用程式中的類型檢查。

在生產環境中禁用 TypeScript 錯誤

當您的專案中存在 TypeScript 錯誤時,Next.js 會使您的 生產構建 (next build) 失敗。

如果您希望 Next.js 即使在應用程式存在錯誤時也能危險地生成生產程式碼,您可以禁用內建的類型檢查步驟。

如果禁用,請確保在構建或部署過程中運行類型檢查,否則這可能非常危險。

打開 next.config.ts 並在 typescript 配置中啟用 ignoreBuildErrors 選項:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  typescript: {
    // !! 警告 !!
    // 危險地允許生產構建即使您的專案存在類型錯誤也能成功完成
    // !! 警告 !!
    ignoreBuildErrors: true,
  },
}

export default nextConfig

小知識:您可以執行 tsc --noEmit 來在構建前自行檢查 TypeScript 錯誤。這對於您希望在部署前檢查 TypeScript 錯誤的 CI/CD 流程非常有用。

自訂類型聲明

當您需要聲明自訂類型時,您可能會想要修改 next-env.d.ts。但是,此檔案是自動生成的,因此您所做的任何更改都將被覆蓋。相反,您應該創建一個新檔案,讓我們稱之為 new-types.d.ts,並在您的 tsconfig.json 中引用它:

tsconfig.json
{
  "compilerOptions": {
    "skipLibCheck": true
    //...省略...
  },
  "include": [
    "new-types.d.ts",
    "next-env.d.ts",
    ".next/types/**/*.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

版本變更

版本變更
v15.0.0新增對 TypeScript 專案的 next.config.ts 支援。
v13.2.0靜態類型連結在 beta 版中可用。
v12.0.0現在預設使用 SWC 來編譯 TypeScript 和 TSX,以實現更快的構建。
v10.2.1當在您的 tsconfig.json 中啟用時,新增對 增量類型檢查 的支援。

On this page