Do you have a set of routines you do before you commit and publish code? These routines could be linting, testing and building the code. Imagine if there was a way to automate all of the routes so they got enforced automatically for your whole team? The solution is to use Git hooks.
Working with Git hooks
Git hooks enable us to hook into Git events and add code to be executed at events such as:
• Post post
Git hooks are set up in the .git folder in a git project. These are written as bash scripts. Unless you lack social skills and wear square glasses you wouldn’t like to write bash scripts (joke).
Husky enables you to specify Node scripts to execute on the different hooks. This can be used eg. to run npm scripts and will make it very easy to hook your Node scripts into the Git events.
Husky can be installed with:
npm i --save-dev husky
Or for YARN users:
yarn add husky -D
Husky can be configured in package.json with a property called husky and supports the Git hooks.
From here you specify regular NPM scripts that will be executed on the specific Git events.
My recommended setup with Git hooks for Angular apps
After having used Git hooks for a while I have developed a couple of preferences for scripts I would like to run before I commit and push code. My husky config looks like this:
For pre-commit hooks, the ideal is to run lint, test, and build of the project. The exception to this is if the test and build phrase takes a considerable long time to execute. If this is the case, start running only linting and tests. If it is still unbearably slow, only run lint, as the build server should catch build and test errors anyways.
Before pushing your code, you want to make sure that you are in sync with the upstream branch. This ensures that you integrate with the upstream branch early, handles merge conflicts and that the project still works properly when integrated with the upstream branch. Alternatively, you can set this command up to do an interactive rebase with:
git rebase origin master -i
Where you might want to squash and rename commits according to Git conventions for the project.
In this post, we saw how Git hooks can ease the development process as you are automatically running trivial pre-commit and pre-post scripts. Also, I gave a recommendation of how to set up Git hooks for Angular apps that I have found very beneficial myself.
Thanks for reading. Remember to follow me on Twitter and leave a comment.
Do you need help with this stuff? Check out my FREE case study.
Did you like this post? New posts every week. Subscribe so you don’t miss any.
I’m Christian, a Danish freelance software developer and entrepreneur. If you like my posts, make sure to follow me on Twitter.
Also published on Medium.