Next.js TypeScript 支持

Next.js 提供了集成的 TypeScript 开发体验,并且开箱即用,类似一个 IDE。以下几个步骤才能在项目中启用 TypeScript。

创建 tsconfig.json

在根目录中创建tsconfig.json。 起初我们不往文件中写内容,使其保持为空。 现在开启服务器。

Next.js将检测Tsconfig.json并在控制台上显示Follwing消息。

$ npm run dev

> nextjs@1.0.0 dev /workspace/node/nextjs
> next dev

ready - started server on 0.0.0.0:3000, url: 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 in your pages directory).

安装 TypeScript

运行npm install命令来安装 TypeScript 和相关库。

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

+ @types/react@17.0.40
+ @types/node@17.0.21
+ typescript@4.6.2
added 6 packages from 69 contributors and audited 32 packages in 14.499s

启动 Next.js 服务器

运行以下命令启动服务器

$ npm run dev

> nextjs@1.0.0 dev /workspace/node/nextjs
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
We detected TypeScript in your project and created a tsconfig.json file for you.

event - compiled client and server successfully in 1086 ms (124 modules)

打开 tsconfig.json

NextJS服务已修改 tsconfig.json。

tsconfig.json

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

创建 hello.ts

在 pages/api 目录中创建 hello.ts,它将充当我们的 rest 服务。

hello.ts

import { NextApiRequest, NextApiResponse } from 'next'

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

启动 Next.js 服务器

运行以下命令启动服务器

$ npm run dev

> nextjs@1.0.0 dev /workspace/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 ,我们将看到以下输出。

Next.js TypeScript 支持

查看笔记

扫码一下
查看教程更方便