Next.js - TypeScript 支持


Next.js 对打字稿有很好的支持。以下是在项目中启用打字稿的几个步骤。

创建 tsconfig.json

在根目录中创建 tsconfig.json。我们最初将其保留为空。现在启动服务器。

Next.JS 将检测 tsconfig.json 并在控制台上显示以下消息。

npm run dev

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

ready - started server on http://localhost: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).
...

安装打字稿

运行 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 http://localhost: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,它将作为我们的休息服务。

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 http://localhost: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"}