What is Husky?
Husky improves your commits and more 🐶 woof!
Husky helps us do more things along with git commands. For example, we can run npm test
in pre-commit
phase and do something else in post-commit
phase
Setup
There is a bit difference between npm version below and above 7, so please check it by
npm -v
Automatic (require npm version > 7)
#For npm
npx husky-init && npm install
#For Yarn 1
npx husky-init && yarn
#For Yarn 2
yarn dlx husky-init --yarn2 && yarn
After executing the command successfully, we need to take a look at the directory tree to make sure .husky/pre-commit
is there.
Manual
- Install
Husky
npm install --save-dev husky
- Enable git hooks
npx husky install
- Add
prepare
script topackage.json
, this script will be trigger enable Git hooks after install. This step also depeneds on our npm version- npm > 7:
npm set-script prepare "husky install"
- npm < 7: copy
"prepare": "husky install"
toscripts
inpackage.json
`
- npm > 7:
Once here, our folder tree look like below.
- Now we need to create a hook by command
husky add
. After executing the below command, a linenpm test
is added to a new filepre-commit
in.husky
, which meansnpm test
will be run before we actually commit.
npx husky add .husky/pre-commit "npm test"
If you use yarn2, here is your reference.
Have fun
Now, depending on our needs, we list out commands in the file pre-commit
. In my case, I want to verify branch name pattern, lint, and test cases
I hope you had fun with git hook. I am really happy to receive your feedback on this article. Thanks for your precious time reading this.
Top comments (0)