add husky pre-commit hook with npm@6 on windows

8.4k Views Asked by At

Environment:

  • git version 2.25.1.windows.1

  • node 12.x

  • Npm 6.14.11

  • husky 7.0.4

  • windows 10

How to correctly setup husky & pre-commit hook? In my case I just want to add npm test script to run, so with every commit tests are run.

1

There are 1 best solutions below

8
On

Although most of things are covered in docs (if not all), I will share steps which I took in order to make this work because I have put several hours effort before finally made it.

  1. npm i husky -D
  2. add new script to package.json - "prepare": "husky install"
  3. execute npm run prepare -> .husky folder is created in project root directory

enter image description here

  1. add new script in package.json file (read more in additional at the bottom):
  • "husky": "node ./node_modules/husky/lib/bin.js"
  1. run npm run husky add ./husky/pre-commit "npm test" -> pre-commit hook is created

enter image description here

  1. execute git commit enter image description here

ADDITIONAL explanation to step 4:

npx husky add .husky/pre-commit "npm test" - this is command stated in docs and many stackoverflow questions/github issues or blogs, but this doesn't work by default on Windows & npm@6 (at least not for me).

Output after this command is like this, it is just showing how to use command, no pre-commit file is created inside .husky folder:

enter image description here

It is documented in husky docs how this can be approached differently, and that is what I tried to do in step 4.

For Windows users, if you see the help message when running npx husky add ..., try node node_modules/.bin/husky add ... instead. This isn't an issue with husky code and is fixed in recent versions of npm 8.

  • And that is all. No additional actions, nor I didn't have to unset git config core.hooksPath.