[Next.js] TypeScript

2022-04-01 hit count image

Let's see how to apply and use TypeScript in the Next.js project.

Outline

In this blog post, I will introduce how to apply and use TypeScript in Next.js.

You can see the full source code of this blog post at the following link.

Blog list

This blog post is a series. If you want to check other blog posts of the series, see the links below.

Add TypeScript to existing project

If you have already a Next.js project based on JavaScript, you need to create a empty tsconfig.json file like the below.

touch tsconfig.json

And then, execute the following command to start the Next.js project.

npm run dev

After that, you can see the following message about installing TypeScript in the terminal.

It looks like you're trying to use TypeScript but do not have the required package(s) installed.

Please install @types/react and @types/node by running:

  npm install --save-dev @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).

So, let’s just follow that. execute the following command to install the libraries for TypeScript.

npm install --save-dev @types/react @types/node

And then, execute the following command again to start the Next.js project.

npm run dev

Now, you can see the project started well unlike before.

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 1832 ms (125 modules)

Also, when you open the tsconfig.json file, you can see the following contents.

{
  "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"
  ]
}

Now, you can change the .js files to .tsx or .ts and use TypeScript in the files.

New project

If you want to create a new Next.js project with TypeScript, execute the command below to create the TypeScript based Next.js project.

npx create-next-app --typescript new-project

When you open the project, you can see TypeScript applied the Next.js project well.

create-next-app with typescript

Completed

Done! we’ve seen how to apply TypeScript to the Next.js project. We’ve seen how to apply TypeScript to the existing project and how to create a new project with TypeScript by create-next-app.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

Posts