简体   繁体   English

如何将 node_modules 与实际的 package.json 同步?

[英]How to sync node_modules with actual package.json?

For example if I've switched branch with git and want to sync node_modules with current package.json .例如,如果我已经用 git 切换了分支并希望将node_modules与当前的package.json同步。 How do I do that?我怎么做?

If your new branch has new npm packages or updated version dependencies, just run $ npm install again after switching branches.如果您的新分支有新的 npm 包或更新的版本依赖项,只需在切换分支后再次运行$ npm install

If your new branch removes npm packages from package.json, run $ npm prune如果您的新分支从 package.json 中删除了 npm 包,请运行$ 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.当我们拉取或检出不同的分支时,当package.json发生变化时,我们可以使用git hooks自动运行npm install

Here is the script that needs to be executed.这是需要执行的脚本。 We basically check whether package.json file is present in the diff.我们主要检查差异中是否存在package.json文件。

#/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 pull - 运行chmod +x post-merge使其可执行,然后mv post-merge .git/hooks/将其放入 git hooks。
  • git checkout - Run chmod +x post-checkout and then mv post-checkout .git/hooks/ git checkout - 运行chmod +x post-checkout然后mv post-checkout .git/hooks/

npm install will install latest versions of packages from packages.json which is often not the desired behaviour. npm install将安装从包的最新版本packages.json这往往是不期望的行为。

When you switch between branches most likely you want the versions fixed in package-lock.json .当您在分支之间切换时,您很可能希望在package-lock.json修复版本。 Since npm 5.7.0 there is a special command npm ci which does that.从 npm 5.7.0 开始,有一个特殊的命令npm ci可以做到这一点。

More details in Why does "npm install" rewrite package-lock.json? 为什么“npm install”重写 package-lock.json?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM