选择性依赖解决方案

Yarn 支持选择性版本解析,它允许你通过 package.json 文件中的 resolutions 字段定义依赖内的自定义包版本或范围。通常,这需要在 yarn.lock 文件中进行手动编辑。

¥Yarn supports selective version resolutions, which lets you define custom package versions or ranges inside your dependencies through the resolutions field in your package.json file. Normally, this would require manual edits in the yarn.lock file.

完整规范请参见 选择性版本决议 RFC

¥See the Selective Versions Resolutions RFC for the full spec.

你为什么想做这个?

¥Why would you want to do this?

  • 你可能依赖于一个不经常更新的软件包,而这又依赖于另一个进行了重要升级的软件包。在这种情况下,如果你的直接依赖指定的版本范围没有覆盖新的子依赖版本,你就会陷入等待作者的困境。

    ¥You may be depending on a package that is not updated frequently, which depends on another package that got an important upgrade. In this case, if the version range specified by your direct dependency does not cover the new sub-dependency version, you are stuck waiting for the author.

  • 你的项目的子依赖获得了重要的安全更新,并且你不想等待直接依赖发布最低版本更新。

    ¥A sub-dependency of your project got an important security update and you don’t want to wait for your direct-dependency to issue a minimum version update.

  • 你依赖于一个未维护但可以工作的包,并且它的依赖之一已升级。你知道升级不会破坏任何东西,并且你也不想复刻你所依赖的包,只是为了更新次要依赖。

    ¥You are relying on an unmaintained but working package and one of its dependencies got upgraded. You know the upgrade would not break things and you also don’t want to fork the package you are relying on, just to update a minor dependency.

  • 你的依赖定义了广泛的版本范围,并且你的子依赖刚刚获得了有问题的更新,因此你希望将其固定到早期版本。

    ¥Your dependency defines a broad version range and your sub-dependency just got a problematic update so you want to pin it to an earlier version.

如何使用它?

¥How to use it?

resolutions 字段添加到 package.json 文件并定义你的版本覆盖:

¥Add a resolutions field to your package.json file and define your version overrides:

package.json

{
  "name": "project",
  "version": "1.0.0",
  "dependencies": {
    "left-pad": "1.0.0",
    "c": "file:../c-1",
    "d2": "file:../d2-1"
  },
  "resolutions": {
    "d2/left-pad": "1.1.1",
    "c/**/left-pad": "^1.1.2"
  }
}

然后运行 yarn install

¥Then run yarn install.

提示与技巧

¥Tips & Tricks

  • 如果你定义了无效的解析(例如使用无效的包名称),你将收到警告

    ¥You will receive a warning if you define an invalid resolution (such as with an invalid package name)

  • 如果你的解析版本或范围无效,你将收到警告。

    ¥You will receive a warning if your resolution version or range is not valid.

  • 如果你的解析版本或范围与原始版本范围不兼容,你将收到警告。

    ¥You will receive a warning if your resolution version or range is not compatible with the original version range.

限制和注意事项

¥Limitations & Caveats

  • 嵌套包可能无法正常工作。

    ¥Nested packages may not work properly.

  • 某些边缘情况可能无法正常工作,因为这是一个相当新的功能。

    ¥Certain edge-cases may not work properly since this is a fairly new feature.