Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sync node_modules with actual package.json?

Tags:

node.js

npm

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

like image 331
gyzerok Avatar asked Sep 01 '15 16:09

gyzerok


People also ask

Do I need to push node_modules in production?

Not committing node_modules implies you need to list all your modules in the package. json (and package-lock. json ) as a mandatory step. This is great because you might not have the diligence to do so, and some of the npm operations might break if you don't.

Can I copy node_modules folder to another project?

You can copy but it will be of no use, its as simple as copy the package. json entry for "react-native-fetch-blob" and do npm install. Also you can do "npm install react-native-fetch-blob@<version>" if you want a specific version else latest will be installed.

How do you sync package json and yarn lock?

Simply install syncyarnlock, and execute with the options applicable to your needs. For example, to sync a project's package. json with the project's yarn. lock, and have the ranges remain intact while updating the versions to reflect what will actually be installed, simply run: syncyarnlock -s -k .

Can I copy node_modules folder?

You can always copy node_modules and then run npm install or npm update in the new project to make sure you've got up-to-date versions. npm will use the files in node_modules as a cache and should only bring down newer content if required. In short: it won't hurt.


2 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

like image 68
Catfish Avatar answered Oct 03 '22 19:10

Catfish


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/
like image 22
Bharathvaj Ganesan Avatar answered Oct 03 '22 17:10

Bharathvaj Ganesan