Managing dependencies across a monorepo often leads to “dependency drift,” where different packages inadvertently use conflicting versions of the same library. By leveraging YAML anchors, you can define a version once and reuse it throughout your pnpm-workspace.yaml file, ensuring all packages remain in sync. This technique is particularly powerful when paired with pnpm’s Catalogs feature.
Prerequisites
- pnpm version 9.5 or higher (required for Catalog support).
- A project configured as a pnpm workspace.
- Basic familiarity with YAML syntax, specifically anchors and aliases.
Implementation Guide
1. Define Shared Versions Using Anchors
Open the pnpm-workspace.yaml file at your project root. Create a custom key to house your version definitions. It is common practice to prefix this key with underscores (e.g., __versions) to indicate that it is for internal reference only and not a native pnpm configuration.
Use the & symbol to define your anchors:
# Shared version expressions (YAML anchors)
__versions:
- &react 19.2.1
- &react_router 7.10.1
- &typescript_eslint 8.57.0
- &vite 7.2.7
- &vitest 4.0.15
- &tailwindcss 4.1.132. Reference Anchors in pnpm Catalogs
pnpm Catalogs allow you to centralize versioning in the workspace configuration and reference them in individual package.json files via the catalog: protocol. Use the * symbol to create aliases for the anchors defined in the previous step.
catalog:
react: *react
react-router: *react_router
vite: *vite
vitest: *vitest3. Apply the Catalog in package.json
In your workspace packages, reference the named catalog entry instead of a hardcoded version number. This ensures the package always inherits the version defined in your central workspace file.
{
"name": "@my-project/web-app",
"dependencies": {
"react": "catalog:",
"vite": "catalog:"
}
}4. Sync the Workspace
Once you have updated your YAML anchors or catalog references, run the following command to propagate the changes across your monorepo:
pnpm installKey Considerations
- Scope Restriction: YAML anchors are limited to the same file. You cannot define an anchor in
pnpm-workspace.yamland reference it directly inside apackage.jsonfile. pnpm’scatalogfeature acts as the necessary bridge between the two. - Interpretation: The
__versionsblock is a standard YAML feature. pnpm does not recognize this block as a specific configuration; instead, the YAML parser resolves all aliases (*) to their anchored values (&) before pnpm processes the configuration logic. - Maintainability: Utilizing a dedicated
__versionsblock establishes a single source of truth for your monorepo. This simplifies major upgrades, allowing you to update a version across dozens of packages by changing a single line.
References
- https://pnpm.io/catalogs
- https://pnpm.io/pnpm-workspace_yaml
- https://yaml.org/spec/1.2.2/#71-alias-nodes