How to sync node_modules with actual package.json?

If your new branch has new npm packages or updated version dependencies, just run $ npm install again after switching branches.

If your new branch removes npm packages from package.json, run $ npm prune


We can make use of git hooks to run the npm install automatically when package.json changes when we pull or checkout to different branch.

Here is the script that needs to be executed. We basically check whether package.json file is present in the diff.

#/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"

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 and then mv post-checkout .git/hooks/

Tags:

Node.Js

Npm