patternjavascriptModerate
pnpm workspaces: linking local packages and filtering commands
Viewed 0 times
pnpm 7+
pnpm workspacesworkspace protocolpnpm filtermonorepo local packagepnpm -r
Problem
In a pnpm monorepo, developers do not know how to add one local package as a dependency of another, or how to run scripts in specific packages without cd-ing into them.
Solution
Define workspaces in pnpm-workspace.yaml, then use workspace protocol for local links and --filter for targeted commands.
# pnpm-workspace.yaml
packages:
- 'packages/*'
- 'apps/*'
# Add local package as dependency (uses symlink, not registry)
pnpm add @myorg/ui --workspace --filter @myorg/web
# Results in package.json: { "dependencies": { "@myorg/ui": "workspace:*" } }
# Run 'build' only in @myorg/ui
pnpm --filter @myorg/ui build
# Run 'test' in all packages that depend on @myorg/ui
pnpm --filter @myorg/web... test
# Run 'build' in all packages, respecting dependency order
pnpm -r build
# pnpm-workspace.yaml
packages:
- 'packages/*'
- 'apps/*'
# Add local package as dependency (uses symlink, not registry)
pnpm add @myorg/ui --workspace --filter @myorg/web
# Results in package.json: { "dependencies": { "@myorg/ui": "workspace:*" } }
# Run 'build' only in @myorg/ui
pnpm --filter @myorg/ui build
# Run 'test' in all packages that depend on @myorg/ui
pnpm --filter @myorg/web... test
# Run 'build' in all packages, respecting dependency order
pnpm -r build
Why
The 'workspace:' protocol tells pnpm to resolve the package from the local workspace instead of the registry. When publishing, pnpm replaces 'workspace:' with the actual version number automatically.
Gotchas
- workspace:* means 'any version from workspace'; workspace:^ and workspace:~ are also valid
- pnpm replaces workspace: references with real semver on 'pnpm publish'
- --filter uses glob patterns; @myorg/* matches all packages in the @myorg scope
- Running pnpm install from the repo root installs all workspaces; avoid running it per-package
Context
Managing a monorepo with multiple packages using pnpm
Revisions (0)
No revisions yet.