Next.js - TypeScript 支援



Next.js 十分支援 TypeScript。以下介紹在專案中啟用 TypeScript 的若干步驟。

建立 tsconfig.json

在根目錄中建立 tsconfig.json。我們先將其保持為空。現在啟動伺服器。

Next.JS 將檢測到 tsconfig.json 並顯示以下控制檯訊息。

npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on https://:3000
It looks like you're trying to use TypeScript but do not have the required package(s) installed.

Please install typescript, @types/react, and @types/node by running:

        npm install --save-dev typescript @types/react @types/node

If you are not trying to use TypeScript, please remove the tsconfig.json file from your package root (and any TypeScript files).
...

安裝 TypeScript

執行 npm install 命令以安裝 TypeScript 和相關庫。

npm install --save-dev typescript @types/react @types/node
...

+ @types/node@14.0.23
+ @types/react@16.9.43
+ typescript@3.9.6
added 5 packages from 72 contributors and audited 839 packages in 27.538s
...

啟動 Next.js 伺服器

執行以下命令以啟動伺服器 -.

npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on https://:3000
We detected TypeScript in your project and created a tsconfig.json file for you.


Your tsconfig.json has been populated with default values.

event - compiled successfully
wait  - compiling...
event - compiled successfully

開啟 tsconfig.json

NextJS 伺服器已修改 tsconfig.json。

{
   "compilerOptions": {
      "target": "es5",
      "lib": [
         "dom",
         "dom.iterable",
         "esnext"
      ],
      "allowJs": true,
      "skipLibCheck": true,
      "strict": false,
      "forceConsistentCasingInFileNames": true,
      "noEmit": true,
      "esModuleInterop": true,
      "module": "esnext",
      "moduleResolution": "node",
      "resolveJsonModule": true,
      "isolatedModules": true,
      "jsx": "preserve"
   },
   "exclude": [
      "node_modules"
   ],
   "include": [
      "next-env.d.ts",
      "**/*.ts",
      "**/*.tsx"
   ]
}

建立 hello.ts

在 pages/api 目錄中建立 hello.ts,它將充當我們的 REST 服務。

import { NextApiRequest, NextApiResponse } from 'next'

export default (_: NextApiRequest, res: NextApiResponse) => {
   res.status(200).json({ text: 'Welcome to TutorialsPoint' })
}

啟動 Next.js 伺服器

執行以下命令以啟動伺服器 -.

npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next

ready - started server on https://:3000
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

驗證輸出

在瀏覽器中開啟 localhost:3000/api/hello,你將看到以下輸出。

{"text":"Welcome to TutorialsPoint"}
廣告
© . All rights reserved.