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.

  1. What are Git hooks?
  2. Running Git hooks with Husky
  3. Adding a post merge Git hook to check lock file changes
  4. Testing the lock file change check
  5. Detecting a lock file change in VS Code

What are Git hooks?

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.

Run Git hooks with Husky

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

How to use Git hooks to detect changes to a lock file and show a message
1.50 GEEK