I recently had to learn yarn workspace
to setup a yarn project template that can be used for easily building new Backstage plugins for our developer portal. I felt it ended up taking longer than it should have to understand setup a simple feature as the documentation is a bit fluffy. This is my attempt at presenting the yarn workspace workflow as distilled as possible.
This approach worked for me with yarn 4.2.2.
Setup
Create your project directory:
mkdir yarn-workspace-monorepo
Initialize a yarn workspace project:
yarn init --workspace
Create your package folders:
mkdir -p packages/package-a packages/package-b
Initialize your packages:
(cd packages/package-a && yarn init) && (cd packages/package-b && yarn init)
You should end up with something like this:
❯ tree
.
├── README.md
├── package.json
└── packages
├── package-a
│ ├── README.md
│ ├── package.json
│ └── yarn.lock
└── package-b
├── README.md
├── package.json
└── yarn.lock
Tada! Your yarn monorepo setup is done.
Features
You can manage global dependencies in the root package.json
for the workspace.
yarn add left-pad
You can manage package-specific dependencies in the package.json
for the respective package.
yarn workspace package-a add left-pad
Yarn dependency resolution magic will handle de-duplication of dependencies and isolating different versions of shared dependencies.
It’s also possible to run tasks in a workspace. For example:
yarn workspaces foreach --all -pt run build
--all
: Runs on all of the workspaces. Workspaces can be filtered with--from
by glob pattern, starting from the current directory downwards.-p
: Runs tasks in parallel.-t
: Respects topological order.
Tips & Tricks
Versioning:
yarn workspace package-a version patch
Publishing, without publishing the workspace root package:
yarn workspaces foreach --no-private -A --topological npm publish