DEV Community

Cover image for Configuration for Husky + pre-commit
Dantis Mai
Dantis Mai

Posted on • Updated on

Configuration for Husky + pre-commit

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

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

image

After executing the command successfully, we need to take a look at the directory tree to make sure .husky/pre-commit is there.
image

Manual

  • Install Husky
npm install --save-dev husky 
Enter fullscreen mode Exit fullscreen mode
  • Enable git hooks
npx husky install
Enter fullscreen mode Exit fullscreen mode
  • Add prepare script to package.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" to scripts in package.json ` image

Once here, our folder tree look like below.
image

  • Now we need to create a hook by command husky add. After executing the below command, a line npm test is added to a new file pre-commit in .husky, which means npm test will be run before we actually commit.


npx husky add .husky/pre-commit "npm test"

image

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
image

Paypal.

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)