Setup Typescript with Nextjs

Tram Ho


Because the day before, I met a library which was quite interesting, but I used typescript, so before I come to that library, I need to set up typescript first for my project, so I have today’s post.

But why is Nextjs and not create-react-app because I want to change the wind a little bit as well as there are some articles about combining create-react-app with typescript so I don’t want to write about it anymore.

If you do not know what nextjs is, it is still scientifically named nextjs, and if you have heard the concept of server side rendering (SSR), it is a library created to help you solve this problem. -react-app can’t do it… You can learn more about it through the homepage or other documents.

As for typescript, if you code JS, you must have heard it, if you summarize it in your opinion, it can be considered as an advanced version of Javascript by the addition of optional static type and object oriented class. This is not available in Javascript. Because it makes organizing and debugging code easier.

Stop chattering, jump into the code to understand gradually:

Install apps:

To use nextjs, there are 2 types of initialization by command or installing dependencies and then configuring from scratch like install next, babel, react …, but to save time, I use method 1 to npx create-next-app nextjs-typescript project, it’s similar to how I created a project by create-react-app: Use the npx create-next-app nextjs-typescript to project nextjs-typescript

Then you add the tsconfig.json file in the root , note, this file is blank, Next.js will automatically fill the data to configure it later.

Next, I run the command npm run dev to run the project, but currently, due to the file ** tsconfig.json **, it will ask me if I want to use typescript and will guide me to install the corresponding packages:

Notice in the image if there is this line: yarn add --dev typescript @types/react @types/node
I always copy that line and install it

Finished, try start now, still the error is red

Read the new build error after installing the piles so that nextjs will be reinstalled in typescript, I run npm run build

So nextjs has detect typescript used instead of js and file ** tsconfig.json ** has been filled.

In the ./pages/_app.js file, I changed the file name to ./pages/app.tsx and revised as follows:

Now try again to see: npm start and success:

If you pay attention, when opening http: // localhost: 3000 / and hard reloading the page, the speed is extremely fast, completely different from create-react-app, which is the biggest advantage of nextjs with CRA.


Hopefully, through the last lesson, you can learn something interesting, see you in the next lesson!

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo