Did you know Git has a way to run commands when certain client-side actions occur? Yep! They’re called Git Hooks and if you aren’t utilizing them, you’re missing out big time.
Wouldn’t it be cool if you could create custom scripts to be run before committing your code? What about right before you push your code to a repository?
While there are many Git Hook solutions out there, my favorite is a little package called Husky.
Installing Husky
Inside your project directory, run npm install husky --save-dev
to add the dependency to your package.json
file.
Real World Examples
Now that Husky is installed, let’s utilize the package and add a few hooks.
First, open your package.json
file and add the following:
{
"husky": {
"hooks": {
"pre-commit": "npm test",
}
}
}
The example above will run your project’s unit tests before committing your code. If the tests fail, your code won’t be committed. This is extremely powerful and helps eliminate broken code being pushed to a repository.
While it’s never good to push broken code, pushing code that isn’t formatted isn’t very nice either.
Take a look at this handy example!
{
"husky": {
"hooks": {
"pre-commit": "ng lint --fix",
}
}
}
This pre-commit hook will ensure that your code is formatted correctly before committing your code. Nice, huh? Remember, Husky allows you to execute custom scripts based on certain actions, so you can make pretty much anything happen - it doesn’t have to be running unit tests or formatting your code.
Taking it a Step Further
Keep in mind that if you’re working on a team, because the Hooks live in the package.json
file, other team members will also be able to take advantage of Husky.
But what if they don’t want to use Husky?
No problem. You can extract the functionality to a different file. And it’s crazy simple.
Create a new file called .huskyrc
and then add your Husky configuration.
{
"husky": {
"hooks": {
"pre-commit": "ng lint --fix",
}
}
}
Just make sure that your .huskyrc
file is ignored in your git commit.
Conclusion
With very minimal set up, you can run your own custom scripts with Husky.
There’s so much you can do - in fact, why not check out all of the Git Hooks that Husky supports?
Sure, a lot of these safeguards and features can be added in your external CI/CD pipelines, but if you don’t have time to set one up, this is a great alternative.
As always, let me know what you think in the comments below!
And if you want to keep up to date with me, feel free to follow me on Twitter or subscribe to my newsletter so you get all of my future articles.
Top comments (0)