Use Husky to manage git hooks
- Hank
- 20 May, 2020
Git hooks is a powerful tool to make your life easier.
It fires off custom scripts when certain important actions occur. one common scene like: you want to lint your code every time when you commit changes, so that your code has a good style and following your team’s code specification. Or you want to run test before pushing your code/
Like many other Version Control Systems, Git has a way to fire off custom scripts when certain important actions occur. There are two groups of these hooks: client-side and server-side. Client-side hooks are triggered by operations such as committing and merging, while server-side hooks run on network operations such as receiving pushed commits. You can use these hooks for all sorts of reasons.
With git hooks, you can make these actions automatically.
While husky is a tool to make Git hooks easier to use. To use it is very easy
First you install it as a development dependency with npm:
npm install husky --save-dev
OR yarn:
yarn add husky -D
Then in your package.json
, add:
{
"husky": {
"hooks": {
"pre-commit": "yarn lint",
"pre-push": "yarn test",
"...": "..."
}
}
}
In the example, we added 2 hooks, pre-commit
and pre-push
, they are meant what they named.
- pre-commit means, every time you run
git commit
, it will runyarn lint
first, and commit the code ifyarn lint
passes without error. - pre-push run command
yarn test
when you rungit push
yarn lint
andyarn test
are commands that you define in yourscripts
in package.json. normally those commands that you runs manually, likeyarn start
oryarn dev
, etc. you can add any command you want and run the, in the hooks.
Pretty straight forward and easy :)