How to keep node_modules in sync with package.json

Today we will be focusing on how to keep our local node_modules up to date whenever the package.json is modified when we pull from remote or switch between branches.

Photo by Thomas Kelley on Unsplash

As JS developer, when we work on projects we frequently need to run npm install command whenever we 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 package then we need to 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 updated.

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 current HEAD and original HEAD. To learn more about refer to this Q&A

To run the above script on

  • git pull — Run chmod +x post-merge to make it executable then mv post-merge .git/hooks/ put it into git hooks.
  • git checkout — Run chmod +x post-checkout to make it executable then mv post-checkout .git/hooks/

References:

This article was originally published at bharathvaj.me

--

--