For example if I've switched branch with git and want to sync node_modules
with current package.json
. How do I do that?
3 Answers
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

- 18,876
- 54
- 209
- 353
-
after running npm install in this case I've stucked with "shasum check failed". Can it be connected with this? Are you sure npm install is valid in such case? – gyzerok Sep 01 '15 at 16:55
-
1I'm positive `npm install` is valid in these cases. You can always try deleting your `node_modules` folder and re-running `npm install`. Also this thread may pertain to your issue. – Catfish Sep 01 '15 at 17:40
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 thenmv post-merge .git/hooks/
put it into git hooks. - git checkout - Run
chmod +x post-checkout
and thenmv post-checkout .git/hooks/

- 3,054
- 1
- 18
- 32
npm install
will install latest versions of packages from packages.json
which is often not the desired behaviour.
When you switch between branches most likely you want the versions fixed in package-lock.json
. Since npm 5.7.0 there is a special command npm ci
which does that.
More details in Why does "npm install" rewrite package-lock.json?

- 3,319
- 28
- 31