如何使用 Yarn 基于锁定文件安装包?

How to install packages based on the lock-file with Yarn?

我们使用 Yarn 安装依赖项。 yarn-lock 文件在 repo 中。如果与 composer for php 相比,我希望当我 运行 yarn install 时,依赖项是根据锁定文件安装的,并且锁定文件不会更改。

使用 composer install for php,您可以在任何环境中为每个包安装相同的版本。我不明白为什么 yarn 不能以类似的方式工作。

我认为 yarn install 锁更新过于频繁,文件失去意义,因为它实际上不锁定版本。还是我使用了错误的命令?

Yarn lock 文件期望按照您解释的方式工作 您的 yarn.lock 文件是自动生成的,应该完全由 Yarn 处理。当您 add/upgrade/remove 依赖于 Yarn CLI 时,它会自动更新您的 yarn.lock 文件。

查看文档:https://yarnpkg.com/en/docs/cli/install

yarn install 用于从 package.json 安装包和从 yarn.lock 安装包。 yarn.lock 文件的存在决定了它是安装操作还是更新操作。

yarn install Install all the dependencies listed within package.json in the local node_modules folder.

The yarn.lock file is utilized as follows:

If yarn.lock is present and is enough to satisfy all the dependencies listed in package.json, the exact versions recorded in yarn.lock are installed, and yarn.lock will be unchanged. Yarn will not check for newer versions. If yarn.lock is absent, or is not enough to satisfy all the dependencies listed in package.json (for example, if you manually add a dependency to package.json), Yarn looks for the newest versions available that satisfy the constraints in package.json. The results are written to yarn.lock.

纱线 1

我认为最好的选择是将 --frozen-lockfile 标志与 yarn install 一起使用。

文档:

If you need reproducible dependencies, which is usually the case with the continuous integration systems, you should pass --frozen-lockfile flag.

还有

Don’t generate a yarn.lock lockfile and fail if an update is needed.


纱线2

如果使用 yarn2 (aka yarn berry) this flag is renamed to --immutable as of v2.0.0.

来自 docs...

If the --immutable option is set (defaults to true on CI since v3.0.0), Yarn will abort with an error exit code if the lockfile was to be modified. For backward compatibility we offer an alias under the name of --frozen-lockfile, but it will be removed in a later release.


这样,如果有人试图将更改推送到 package.json,比如将 react^16.8.0 升级到 ^16.10.0,而不更新 yarn.lock 文件。然后它会在 CI 中出错,如下所示。

> yarn install --frozen-lockfile
error Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.

解决您的评论:

I think that with yarn install the lock gets updated too often and the file loses its point since it actually does not lock versions. Or am I using the wrong commands?

Yarn/npm 只是按照您的吩咐去做。如果您将 package.json 中的版本设置为 "react": "16.8.0",它将永远不会更新 yarn.lock,但是当使用任何 npm ranges like the Caret(即 "react": "^16.8.0")时,yarn/npm 将解析为满足范围 you specified 的 highest/newest 版本。 拥有所有的力量!


更新

我发现了一个小的边缘案例。如果您在 ci 中 运行 yarn add,例如对于 ci 唯一的依赖项,它将更新锁定文件并为所有依赖项执行安装 ci是的。例如....

# Add ci dep
yarn add codecov

# Install all deps from yarn.lock
yarn install --frozen-lockfile

这不会像您预期的那样出错。相反,将 --frozen-lockfile 添加到像这样的 yarn add 命令...

# Add ci dep
yarn add codecov --frozen-lockfile

# Install all deps from yarn.lock
yarn install --frozen-lockfile