DEV Community

Neelesh Ranjan Jha
Neelesh Ranjan Jha

Posted on • Edited on

Pre Commit Checks using Husky

Introduction

Are you tired of pushing code that breaks down during build phase because some linting check or typescript check had failed? Well worry not because this post is going to ensure it does not happen again.

Pre Requisites

We need certain packages in our project before starting -

yarn add -D husky lint-stage
Enter fullscreen mode Exit fullscreen mode

Husky is going to run the commands we specify before the commit happens.

Initialising Husky

In your project's terminal, type

npx init husky
Enter fullscreen mode Exit fullscreen mode

You will see that a folder with the name .husky is created in your project's directory.

Editing Package.json

Add the following in the scripts part of your package.json

"postinstall": "husky install",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"tsc": "tsc --noEmit"
Enter fullscreen mode Exit fullscreen mode

Also add this after the scripts part in package.json

"lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix"
    ]
},
Enter fullscreen mode Exit fullscreen mode

in the end, your package.json would like this

  "scripts": {
    "dev": "next dev -p 3001",
    "devEnv": "cpy .env.dev .env",
    "build": "next build",
    "start": "next start",
    "postinstall": "husky install",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
    "tsc": "tsc --noEmit"
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix"
    ]
  },
Enter fullscreen mode Exit fullscreen mode

Editing the Pre-Commit file

There is a pre commit in the .husky folder. We need to edit it and add the following

yarn tsc
yarn eslint
Enter fullscreen mode Exit fullscreen mode

Testing

Now in your code, create an intentional Typescript error or an disobey an ESLint Rule. Now try to commit the file and you will get an error and the code won't be committed and you will get an error in the git logs.

Pre Commit Error

Edit: If you still want to commit your code, do the following

git commit -m "commit regardless of errors" --no-verify
Enter fullscreen mode Exit fullscreen mode

Conclusion

Viola, that's it, now you won't be able to commit code with typescript errors and linting errors anymore and hopefully your build will stop failing as often.

Top comments (2)

Collapse
 
phryte profile image
PHRYTE

Great post! Another useful step that you can add in your pre commit hook is formatting (using prettier)

Collapse
 
neeleshrj profile image
Neelesh Ranjan Jha

Great addition! We can fix the eslint checks as well!