NextJS + TypeScript

Tram Ho

Create projects with Next.js and TypeScript

This article I wrote as a note for the times when I need to create a project. You can refer or if you find it suitable ^^

In the past, I used to use js more than ts , sometimes I have a grudge against ts because I find it quite confusing, but after using it for a while, I find it quite interesting.

For those of you who are like me and want to try and ts what’s fun, you can set up a project and feel it for yourself

  • Next v13
    • Node 14.6.0 or newer.
    • MacOS, Windows (including WSL), and Linux are supported.
  • TypeScript v4.9.

Begin

There are 2 ways to setup TypeScript with Nextjs:

  • Use create-next-app .
  • Add TypeScript to the current project.

create-next-app

We can start a Next.js project with TypeScript by using the CLI tool create-next-app and adding the --typescript or --ts flag behind it.

Add TypeScript to existing Next.js project

First, we need to create a file tsconfig.json in the root directory of the project: touch tsconfig.json

Then you run the command to start the application, here the scripts to start your application are yarn dev .

Next.js will notice and try to install TypeScript related packages.

After the installation is complete, open the tsconfig.json file and you will see it like below:

If you pay attention, you will see a file next-env.d.ts , this file ensures the Next.js types will be picked up by the TypeScript compiler.

At this point, adding TypeScript to the Next.js project is done. You can start coding.

For those of you who are new to TypeScript and Next.js, you can refer to the 2 links below to practice ^^

React + TypeScript cheatsheet: https://react-typescript-cheatsheet.netlify.app/

NextJS + TypeScript: https://nextjs.org/docs/basic-features/typescript

Conclusion

Installing Next.js with TypeScript is really not too difficult, isn’t it,

During installation, there may be some errors related to Next.js and TypeScript versions, but it is not too complicated to solve.

See you in other posts!!!

Share the news now

Source : Viblo