且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 `npm install` 会为同一个 `package.json` 文件生成不同的 `package-lock.json` 文件?

更新时间:2022-10-16 23:34:24

来自 https://docs.npmjs.com/files/package-locks

从概念上讲,npm-install 的输入"是 package.json,而它的输出"是一个完整的 node_modules 树:您声明的依赖项的表示.在理想的世界中,npm 会像这样工作纯函数:相同的 package.json 应该在任何时候生成完全相同的 node_modules 树.在某些情况下,确实如此.但在许多其他情况下,npm 无法做到这一点.有多种原因:>

  • 可能使用了不同版本的 npm(或其他包管理器)来安装包,每个版本使用的安装算法略有不同."

package-lock 文件将确保不会因包版本略有不同而中断,在同一台机器上同时运行 npm install 并不能保证获得所有依赖项的相同版本.

另一点可以阐明包文件与包锁定文件的不同之处.两个相同的 package.json 文件并不能保证相同的 node_modules 文件夹结构.但是两个相同的包锁文件将保证完全相同的 node_modules 文件结构.

Here is the relevant part of my package.json file:

  "devDependencies": {
    "ajv": "^6.0.0",
    "webpack": "^4.0.0",
    "websocket": "^1.0.0",
    "bignumber.js": "^7.0.0",
    "decimal.js": "^10.0.0",
    "truffle": "4.1.11",
    "ganache-cli": "6.1.0",
    "solidity-coverage": "0.5.4",
    "ethereumjs-testrpc-sc": "6.1.2",
    "web3": "1.0.0-beta.34"
  }

I have this file in two different repositories, on the same PC.

When I run npm install in each one of these repositories at the same time, I get a different package-lock.json file in each repository.

How could this be?

Here is a possible clue:

If I delete the package-lock.json file beforehand, then npm install aborts with an error.

So the answer to my question is possibly related to the fact that npm install relies on an already existing package-lock.json file.

And initially, I had different package-lock.json files in these repositories, because the corresponding package.json files were different.

Now that I've changed the package.json file in one of the repositories to be identical to the other, I am expecting that the corresponding package-lock.json files will also become identical.

From https://docs.npmjs.com/files/package-locks

"Conceptually, the "input" to npm-install is a package.json, while its "output" is a fully-formed node_modules tree: a representation of the dependencies you declared. In an ideal world, npm would work like a pure function: the same package.json should produce the exact same node_modules tree, any time. In some cases, this is indeed true. But in many others, npm is unable to do this. There are multiple reasons for this:

  • different versions of npm (or other package managers) may have been used to install a package, each using slightly different installation algorithms."

The package-lock file is going to ensure that nothing breaks due to having slightly different package versions, running npm install on the same machine at the exact same time is not going to guarantee that the same version of all dependencies is acquired.

Another point that may clarify how a package file differs from a package-lock file. Two identical package.json files do not guarantee the same node_modules folder structure. But two identical package-lock files will guarantee the exact same node_modules file structure.