要锁定安装在项目上的依赖项的版本,命令 npm install
会创建一个名为 package-lock.json
的文件。这是从 Node.js v8.0.0 开始制作的和 npm v5.0.0 ,正如你们中的一些人可能知道的那样。
尽管有 Node.js和 npm关于提交这个文件的建议,关于何时应该避免这样做的几个问题,也是一种选择。通常我们会在项目中做出 promise ,然而,这是一个特殊的问题。
虽然我们应该默认提交 package-lock.json
文件,但我们有一个不应该提交的特定情况。例如,如果我们想测试我们项目依赖项的最新版本,可以选择将 package-lock.json
添加到 .gitignore
中。
所以,问题如下:
package-lock.json
文件是否应该添加到.gitignore
中?- 是否有任何我们必须或不得这样做的特殊情况?
最佳答案
不,package-lock.json
不应该添加到 .gitignore
。相反,我强烈建议:
- 将您的
package-lock.json
添加到您的版本控制存储库 - 在本地和部署管道中构建应用程序时,使用
npm ci
而不是npm install
。
(ci
命令从 npm@5.7 开始可用,如果有疑问通过以下方式升级您的 npm:
npm install -g npm
。)
npm install
命令的最大缺点之一是它可能会改变 package-lock.json
的意外行为,而 npm ci
仅使用 lockfile 中的版本,如果 package-lock.json
和 package.json
不同步,则会产生错误。
另外,npm ci
要求 package-lock.json
的存在,如果不存在则会打印错误。
有一个强大的用例可以信任项目的依赖项以可靠的方式在不同机器上重复解决。
此外,npm ci
在添加依赖项之前核对整个 node_modules
文件夹,确保您使用实际依赖项而不是本地更改,同时仍然比普通的更快 npm install
.
从 package-lock.json
中,您可以得到确切的信息:一个已知可工作的状态,始终具有完全相同的依赖关系树。
过去,我的项目没有 package-lock.json
/npm-shrinkwrap.json
/yarn.lock
文件的构建有一天会失败,因为随机依赖项得到了破坏性更新。 (虽然很多库都遵守 semvar 版本控制指南,但您不能保证它们不会在小升级时中断。)
这些问题很难解决,因为您有时不得不猜测上一个工作版本是什么。
关于测试您项目的最新依赖项:这就是 npm update
的用途,我认为它应该由开发人员运行,该开发人员也在本地运行测试,解决问题如果它们可能出现,然后由谁提交更改的 package-lock.json
。 (如果升级失败,他们可以恢复到上次工作的 package-lock.json
。)
此外,我很少一次升级所有依赖项(因为这也可能需要进一步维护),但我宁愿挑选我需要的更新(例如 npm update {dependency}
或 npm install {dependency}@2.1.3
)。这也是我将其视为手动维护步骤的另一个原因。
如果您真的想实现自动化,您可以为以下人员创建工作:
- checkout 存储库
- 运行 npm 更新
- 运行测试
- 如果测试通过,则提交并推送到存储库
- 否则失败并报告问题需要手动解决
这是我会看到托管在 CI 服务器上的东西,例如Jenkins,不应该通过上述原因通过将文件添加到.gitignore
来实现。
或至quote npm doc :
It is highly recommended you commit the generated package lock to source control: this will allow anyone else on your team, your deployments, your CI/continuous integration, and anyone else who runs npm install in your package source to get the exact same dependency tree that you were developing on. Additionally, the diffs from these changes are human-readable and will inform you of any changes npm has made to your node_modules, so you can notice if any transitive dependencies were updated, hoisted, etc.
关于 difference between npm ci
vs npm install
:
- The project must have an existing package-lock.json or npm-shrinkwrap.json.
- If dependencies in the package lock do not match those in package.json,
npm ci
will exit with an error, instead of updating the package lock.npm ci
can only install entire projects at a time: individual dependencies cannot be added with this command.- If a
node_modules
is already present, it will be automatically removed beforenpm ci
begins its install.- It will never write to
package.json
or any of the package-locks: installs are essentially frozen.
关于javascript - 是否应该将 package-lock.json 文件添加到 .gitignore 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524417/