DEV Community

Gabor Chromy
Gabor Chromy

Posted on

Add Typescript type check to next.js

Default the next.js doesn't run typescript type check.
When I started to create my blog in next.js and in typescript soon I needed to check the project for type errors.
Here is the way how I made it to do that for me.
This is my first post, so I hope it helps others.

This assumes you already set up the project with typescript.

First we need to add fork-ts-checker-webpack-plugin to the project as a dev dependency

$ yarn add -D fork-ts-checker-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Second, we need to create a next.config.js (if was not created previously), in the project root and add config:

/* eslint-disable @typescript-eslint/no-var-requires */

const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");

module.exports = {
 /**
  * Custom Webpack Config
  * https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config
  */
 webpack(config, options) {
   const { dev, isServer } = options;

   // Do not run type checking twice:
   if (dev && isServer) {
     config.plugins.push(new ForkTsCheckerWebpackPlugin());
   }

   return config;
 },
};

Enter fullscreen mode Exit fullscreen mode

Now you can start development in the well known way, and on every save you should see issue checking messages:

$ next dev
ready - started server on http://localhost:3000
Issues checking in progress...
No issues found.
event - compiled successfully
event - build page: /
wait  - compiling...
No issues found.
Enter fullscreen mode Exit fullscreen mode

Good luck!

Top comments (2)

Collapse
 
cbdeveloper profile image
cbdeveloper

Thanks for the article. Why if (dev && isServer) and not just if (dev)? Why would you need it on server?

Collapse
 
julioflima profile image
Julio Lima

Fucking awesome.