Yarn workspaces explained, quickly

October 2024 · 2 minute read

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

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