网页
综合
更新时间 2026-11-14 16:25:23
Constraints | Yarn
自动蜘蛛
yarnpkg.com
正文约 2259 字
This page documents the new JavaScript-based constraints. The older constraints, based on Prolog, are still supported but should be considered deprecated. Their documentation can be found here.
Constraints allow enforcement of rules across workspace packages. For example, these rules might include the following:
Our constraint engine currently supports two main targets:
It currently doesn't support the following, but might in the future (PRs welcome!):
Constraints are created by adding a yarn.config.cjs file at the root of your project (repository). This file should export an object with a constraints method. This method will be called by the constraints engine, and must define the rules to enforce on the project, using the provided API.
For example, the following yarn.config.cjs will enforce that all react dependencies are set to 18.0.0.
And the following will enforce that the engines.node field is properly set in all workspaces:
As much as possible, constraints are defined using a declarative model: you declare what the expected state should be, and Yarn checks whether it matches the reality or not. If it doesn't, Yarn will either throw an error (when calling yarn constraints without arguments), or attempt to automatically fix the issue (when calling yarn constraints --fix).
Because of this declarative model, you don't need to check the actual values yourself. For instance, the if condition here is extraneous and should be removed:
Yarn ships types that make it easier to write constraints. To use them, add the dependency to your project:
Then, in your yarn.config.cjs file, import the types, in particular the defineConfig function which automatically type the configuration methods:
You can also retrieve the types manually, which can be useful if you extract some rules into helper functions:
You can alias the types to make them a little easier to use:
This section regroups a couple of constraint examples. We are thinking to provide some of them as builtin helpers later on, although they tend to often contain some logic unique to each team / company.
This code ensures that no two workspaces in your project can list the same packages in their dependencies or devDependencies fields but with different associated references.
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。