TExcelTAD

Yarn Constraints

In a monorepo with thirty packages, conventions drift: one package pins lodash 4.17, another 4.18; someone forgets the license field; a deprecated package sneaks back in. Code review catches some of it. Constraints catch all of it: rules about package.json files, written in JavaScript in yarn.config.cjs, checked by yarn constraints and often fixed automatically with --fix.

The API in brief

yarn.config.cjs exports a constraints function. Yarn passes it a context whose Yarn object queries the project:

Call Returns
Yarn.workspaces() every workspace (with .ident, .cwd, .manifest)
Yarn.workspace({ ident }) one workspace
Yarn.dependencies({ ident, type }) every dependency entry across the project (with .workspace, .range, .type)
workspace.set(path, value) require a field to have a value (fixable)
workspace.unset(path) require a field to be absent (fixable)
dependency.update(range) require a range (fixable)
dependency.delete() require the dependency to be removed (fixable)
workspace.error(msg), dependency.error(msg) report a problem that can't be fixed automatically

A rule set for a real monorepo

js
// yarn.config.cjs
/** @type {import('@yarnpkg/types')} */
module.exports = {
  async constraints({ Yarn }) {
    // 1. Every workspace declares the MIT license.
    for (const ws of Yarn.workspaces()) ws.set('license', 'MIT');

    // 2. A dependency used in several workspaces uses one range everywhere:
    //    the range of the first workspace that declares it wins.
    const ranges = new Map();
    for (const dep of Yarn.dependencies()) {
      if (dep.type === 'peerDependencies') continue;
      const wanted = ranges.get(dep.ident) ?? dep.range;
      ranges.set(dep.ident, wanted);
      dep.update(wanted);
    }

    // 3. left-pad is banned: String.prototype.padStart exists.
    for (const dep of Yarn.dependencies({ ident: 'left-pad' }))
      dep.error('left-pad is deprecated; use String.prototype.padStart');
  },
};

Here it is against a monorepo that breaks all three rules:

bash · try it yourself
mkdir -p mono/packages/{api,ui} && cd mono
echo '{ "name": "mono", "private": true, "license": "MIT", "packageManager": "yarn@4.18.1", "workspaces": ["packages/*"] }' > package.json
touch yarn.lock
echo '{ "name": "@mono/api", "version": "1.0.0", "license": "MIT", "dependencies": { "lodash": "^4.18.1", "ms": "^2.1.3" } }' > packages/api/package.json
echo '{ "name": "@mono/ui", "version": "1.0.0", "dependencies": { "lodash": "4.17.21", "left-pad": "^1.3.0" } }' > packages/ui/package.json
cat > yarn.config.cjs <<'JS'
module.exports = {
  async constraints({ Yarn }) {
    for (const ws of Yarn.workspaces()) ws.set('license', 'MIT');
    const ranges = new Map();
    for (const dep of Yarn.dependencies()) {
      if (dep.type === 'peerDependencies') continue;
      const wanted = ranges.get(dep.ident) ?? dep.range;
      ranges.set(dep.ident, wanted);
      dep.update(wanted);
    }
    for (const dep of Yarn.dependencies({ ident: 'left-pad' }))
      dep.error('left-pad is deprecated; use String.prototype.padStart');
  },
};
JS
yarn install > /dev/null
yarn constraints; echo "exit code: $?"
➤ Errors prefixed by '⚙' can be fixed by running yarn constraints --fix

└─ @mono/ui@workspace:packages/ui
   ├─ left-pad is deprecated; use String.prototype.padStart
   ├─ ⚙ Missing field license; expected "MIT"
   └─ ⚙ Invalid field dependencies["lodash"]; expected "^4.18.1", found "4.17.21"
exit code: 1

Each problem is reported against the workspace and field it concerns, with ⚙ marking the ones --fix can repair. The exit code is 1, so yarn constraints in CI blocks the pull request.

Fixing automatically

bash · try it yourself
mkdir -p mono/packages/{api,ui} && cd mono
echo '{ "name": "mono", "private": true, "license": "MIT", "packageManager": "yarn@4.18.1", "workspaces": ["packages/*"] }' > package.json
touch yarn.lock
echo '{ "name": "@mono/api", "version": "1.0.0", "license": "MIT", "dependencies": { "lodash": "^4.18.1" } }' > packages/api/package.json
echo '{ "name": "@mono/ui", "version": "1.0.0", "dependencies": { "lodash": "4.17.21", "left-pad": "^1.3.0" } }' > packages/ui/package.json
cat > yarn.config.cjs <<'JS'
module.exports = {
  async constraints({ Yarn }) {
    for (const ws of Yarn.workspaces()) ws.set('license', 'MIT');
    const ranges = new Map();
    for (const dep of Yarn.dependencies()) {
      if (dep.ident === 'left-pad') continue;
      const wanted = ranges.get(dep.ident) ?? dep.range;
      ranges.set(dep.ident, wanted);
      dep.update(wanted);
    }
    for (const dep of Yarn.dependencies({ ident: 'left-pad' })) dep.delete();
  },
};
JS
yarn install > /dev/null
yarn constraints --fix; echo "exit code: $?"
cat packages/ui/package.json
yarn install > /dev/null && yarn why lodash
yarn constraints && echo "constraints pass"
exit code: 0
{
  "name": "@mono/ui",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "^4.18.1"
  },
  "license": "MIT"
}
├─ @mono/api@workspace:packages/api
│  └─ lodash@npm:4.18.1 (via npm:^4.18.1)
│
└─ @mono/ui@workspace:packages/ui
   └─ lodash@npm:4.18.1 (via npm:^4.18.1)
constraints pass

This version of the config delete()s left-pad instead of reporting it, and skips it in the alignment loop. Without that continue, two rules would disagree about the same field (update('^1.3.0') says keep it, delete() says remove it), and Yarn refuses to guess:

text
└─ @mono/ui@workspace:packages/ui
   └─ Conflict detected in constraint targeting dependencies["left-pad"]; conflicting values are:
      ├─ "^1.3.0" at Object.constraints (/home/learner/mono/yarn.config.cjs:8:11)
      └─ undefined at Object.constraints (/home/learner/mono/yarn.config.cjs:10:75)

With the rules consistent, so --fix repaired everything: the license was added, lodash aligned to ^4.18.1, left-pad removed. After the next install there's a single lodash in the project.

When to use constraints

Rule Why
one version of each dependency smaller bundles, no "two Reacts", one place to upgrade
internal dependencies use workspace:^ never resolve an internal package from the registry
required fields (license, repository, engines) publishable packages stay publishable
private: true on apps apps can't be published by accident
banned packages deprecated, vulnerable, or licence-incompatible
peer ranges match the version used in devDependencies libraries test against what they promise

pnpm's answer to rule 1 is the catalog: versions are written once in pnpm-workspace.yaml and referenced as catalog:. Constraints are more general (any field, any rule), catalogs are simpler (no rules, one source of truth).

Note: Before Yarn 4, constraints were written in Prolog (constraints.pro). That format still works but is deprecated; new projects should use yarn.config.cjs, which also gets type checking through the @yarnpkg/types package.

Test yourself

What does yarn constraints --fix do with a dependency.update('^4.18.1') violation?

  1. Reports it only
  2. Rewrites the range in that workspace's package.json
  3. Installs both versions
  4. Publishes a new version

Where are Yarn 4 constraints written?

  1. constraints.pro in Prolog only
  2. yarn.config.cjs in JavaScript
  3. .yarnrc.yml
  4. package.json under "constraints"

Why is yarn constraints useful in CI?

  1. It installs faster
  2. It exits non-zero when any rule is broken, blocking the change
  3. It publishes packages
  4. It updates the lockfile