How to keep node_modules in sync with package.json?

date
Oct 29, 2020
slug
how-to-keep-node_modules-in-sync-with-package.json
status
Published
tags
npm
nodejs
summary
Learn how to keep node_modules in sync with package.json
type
Post
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

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)
  1. Make it executable by running chmod +x {HOOK_NAME}
  1. 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

References


© Bharathvaj Ganesan 2020 - 2023