All Articles

How to keep node_modules in sync with package.json

2 min read

As a JS developer, while working on projects we frequently need to run npm install command on git pull or checkout to a different git branch where package.json is modified.

In majority of the cases, the dependencies won’t cause any issues, but if there any breaking change introduced by the dependency packages then we need to do reinstall. We somehow forget to run the command (I mostly forget it at least 😛).

How do we automate this?

Well, it quite simple. Hooks!!!

Yes. Git hooks.

We can make use git hooks to trigger npm install command if a package.json file has been modified.

Script to run inside git hooks.

#/usr/bin/env bash

changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

check_run() {
	echo "$changed_files" | grep --quiet "$1" && eval "$2"

check_run package.json "npm install"

Here we check whether package.json file is present in the diff between the current HEAD and original HEAD. To learn more about refer to this Q&A

In order to do the magic,

  1. Save the script with git hook name (eg. post-merge)
  2. Make it executable by running chmod +x {HOOK_NAME}
  3. Finally put the file into git hook by mv {HOOK_NAME} .git/hooks/

Git Hooks

  • post-merge — Invoked by git pull / git merge
  • post-checkout — Invoked by git checkout / git clone


Bharathvaj Ganesan

Software developer 👨🏻‍💻 Loves building things over web...
Design Systems @chargebee!!!
Bharathvaj Ganesan on Twitter