DEV Community

Cover image for Effectively using Pre-commit hooks in Git for Javascript Developers.
Rajiv K.R.
Rajiv K.R.

Posted on • Originally published at


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
Enter fullscreen mode Exit fullscreen mode

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"

Enter fullscreen mode Exit fullscreen mode

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'"
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!