📅  最后修改于: 2020-10-22 06:48:29             🧑  作者: Mango
Next.js对打字稿具有出色的支持。以下是在项目中启用打字稿的几个步骤。
在根目录中创建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命令以安装打字稿和相关库。
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
...
运行以下命令以启动服务器-。
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
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"
]
}
在pages / api目录中创建hello.ts,它将为我们提供休息服务。
import { NextApiRequest, NextApiResponse } from 'next'
export default (_: NextApiRequest, res: NextApiResponse) => {
res.status(200).json({ text: 'Welcome to TutorialsPoint' })
}
运行以下命令以启动服务器-。
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"}