Add a Pre-Commit Git Hook to a Node.js Repo with Husky

We can easily add a pre-commit hook to a NodeJS repository using the Husky package. The example below shows how this works.

First install Husky:

$ npm install husky

Now add a file .huskyrc in the root of your repo with the JSON below:

{
  "hooks": {
    "pre-commit": "echo 'commit event detected'"
  }
}

We can test this out to prove it is working:

$ git add .
$ git commit -m "hook testing" 
husky > pre-commit (node v11.6.0)
commit event detected

The hook executed but the commit succeeds.

To demonstrate how the hook can fail and prevent commits, we can set the exit status code of the command:

{
  "hooks": {
    "pre-commit": "echo 'commit event detected'; exit 1"
  }
}

Now we will get the following result:

$ git commit -m "hook test"
husky > pre-commit (node v11.6.0)
commit event detected
husky > pre-commit hook failed (add --no-verify to bypass)

This shows that commits will not be allowed if the exit status code of the command in the pre-commit hook is 1 (error).

Naturally we want to do something useful with the pre-commit hook, e.g. making sure all unit tests pass: a command like Jest will set the exit status to 1 (error) if there failing tests. Assuming we have defined npm test with a command like Jest or similar we could set our hook to:

{
  "hooks": {
    "pre-commit": "npm test"
  }
}

Now committing code which fails unit tests will be impossible, unless we explicitly bypass the hook like this:

$ git commit -m "hook test" --no-verify

References

https://www.npmjs.com/package/husky

Leave a Reply

Your email address will not be published. Required fields are marked *