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

- Enable git hooks
Enter fullscreen mode Exit fullscreen mode

npx husky install

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s0o6oq1dqngrjpttsiu2.png)

Once here, our folder tree look like below. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avhpmlo0rqafqel6o3j1.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/khzirhq9u0dvov4y931q.png)

*If you use yarn2, [here](https://typicode.github.io/husky/#/?id=yarn-2) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhgy3ws6egqh57nupnh0.png)

[Paypal](https://paypal.me/DantisMai).

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

Top comments (1)

Collapse
 
edjchapman profile image
Ed Chapman

This is just copied from the documentation?