Effectively using Pre-commit hooks in Git for Javascript Developers.

Effectively using Pre-commit hooks in Git for Javascript Developers.

One of the pain points of being Javascript developers is not catching a few basic errors before it comes back to haunt you.

Even with the most increasing usage of Typescript, year after year, still not all existing code bases are going to be migrated soon.

The assumption here is that will all the code linters set up, Eslint or Tslint, if you need help with that, please read my blog here, this is an attempt to propose an effective solution using a couple of famous packages, Husky and Lint staged.


You have eslint set up, you can read more on that in my linting blog here. You will need to be using node version > 10 for activating husky.

Pre-commit hooks

When you have made all the code changes are ready to push your code(hoping to save the world at that time!), you will use git commit command to push the files that you have made changes to. Pre-commit hooks will be running before that commit could potentially destroy the world.


We need to install the packages as dev dependencies first.

npm install husky lint-staged --dev

Going with our assumption that all the linting rules are already set up, we will add this to our package.json

 "husky": {
    "hooks": {
      "pre-commit": "lint-staged"

For the lint-staged, feel free to add the checks that you wish to be passed before accepting the commit.

  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "npm test",
    "*.css" : [
    "stylelint 'src/**/*.css'"

Seeing this in Action

When you are committing, you will see the hook getting run and throw an error. Here we have tried to reassign the value of const variable, that was caught by our linter.


You can have runners set up to track code coverage on each commit by running test to only the staged files. There are many perks for using this and setting up can be done in no time.