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.