24

For example if I've switched branch with git and want to sync node_modules with current package.json. How do I do that?

gyzerok
  • 1,338
  • 2
  • 11
  • 26

3 Answers3

29

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

Catfish
  • 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
  • 1
    I'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
2

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/
Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
0

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?

Stalinko
  • 3,319
  • 28
  • 31