When we’re working on a collaborative team, from time to time a developer has to add a new package to a branch which is then merged into master. Someone might be unaware of it and just pull master and run the app only to have it crash due to the missing package. Let’s see how we can use Git hooks to detect changes to a package.json
or a yarn.lock
and display a message prompting the user to install the missing dependencies.
Git hooks are fired when some Git event occurs such as a new commit, pushing commits to an online branch, pull commits, checkout a branch or merge a branch. These processes end with 0 when they end correctly or some other value when they end incorrectly.
If the process hooked ends with 0, the Git action proceeds. Otherwise, the Git action is blocked. For example, if you configure a pre-commit Git hook to lint your code, Git will run this when you do a git commit
. If the lint fails, the commit won’t go through.
Git hooks are something integrated into Git and the list of hooks is very extensive. For example, you have pre-push, post-commit, post-checkout, post-merge, and many other Git hooks.
To run some tasks when the Git hooks are fired we can use the Husky package for Node.js. Husky allows us to specify in a package.json
file which scripts to run when a Git hooks is fired. Install the Husky package with NPM:
npm i -D husky
or Yarn:
yarn add -D husky
Now you need to initialize Husky for Git hooks. If you use NPM:
npx husky install
and if you use Yarn
yarn husky install
and that’s it, you’ve now installed and configured Husky to run Git hooks. It’s finally time to define a hook!
#technology #git #node.js