Next.js - Suporte TypeScript
Next.js, tem excelente suporte para typescript. A seguir estão algumas etapas para habilitar o texto digitado no projeto.
Crie tsconfig.json
Crie tsconfig.json no diretório raiz. Estamos mantendo-o vazio inicialmente. Agora inicie o servidor.
O Next.JS detectará tsconfig.json e mostrará a mensagem a seguir no console.
npm run dev
> [email protected] 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).
...
Instale o typescript
Execute o comando npm install para instalar o typescript e as bibliotecas relacionadas.
npm install --save-dev typescript @types/react @types/node
...
+ @types/[email protected]
+ @types/[email protected]
+ [email protected]
added 5 packages from 72 contributors and audited 839 packages in 27.538s
...
Inicie o servidor Next.js
Execute o seguinte comando para iniciar o servidor -.
npm run dev
> [email protected] 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
Abra tsconfig.json
O servidor NextJS modificou o 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"
]
}
Crie hello.ts
Crie hello.ts no diretório pages / api que atuará como um serviço de descanso para nós.
import { NextApiRequest, NextApiResponse } from 'next'
export default (_: NextApiRequest, res: NextApiResponse) => {
res.status(200).json({ text: 'Welcome to TutorialsPoint' })
}
Inicie o servidor Next.js
Execute o seguinte comando para iniciar o servidor -.
npm run dev
> [email protected] 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
Verificar saída
Abra localhost: 3000 / api / hello em um navegador e você verá a seguinte saída.
{"text":"Welcome to TutorialsPoint"}