zaro

How Do I Set Up Yarn Workspaces In My Project?

Published in Yarn Workspaces Setup 2 mins read

You don't "install" Yarn Workspaces like a typical software package. Instead, Yarn Workspaces is a feature built into Yarn itself that you enable and configure directly within your project's root package.json file.

Setting up Yarn Workspaces involves a simple configuration step to tell Yarn where to find the individual packages (workspaces) within your larger project repository.

Declaring Your Workspaces

The primary step to enable Yarn Workspaces is to modify the package.json file located at the root of your monorepo project.

As stated in the documentation:

To declare a workspace, all you have to do is add a workspaces array to the root package.json file, and list relative glob patterns pointing to your workspaces' folders.

This workspaces array contains a list of file path glob patterns. These patterns tell Yarn which directories within your project should be treated as workspaces. Each directory matching a pattern should typically contain its own package.json file, representing an independent package or module.

Example package.json

Here is a common example demonstrating how to declare workspaces located within a packages directory:

{
  "name": "my-monorepo-root",
  "version": "1.0.0",
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "build": "yarn workspaces run build",
    "test": "yarn workspaces run test"
  }
}

In this example:

  • "private": true is often added to the root package.json to prevent accidentally publishing the root itself to a registry like npm.
  • "workspaces": ["packages/*"] is the crucial part. This array tells Yarn to look for subdirectories directly inside the packages folder and treat each one as a workspace. The * is a glob pattern matching any subdirectory name (e.g., packages/my-component, packages/my-utility).

You can specify multiple patterns if your workspaces are spread across different top-level directories:

"workspaces": [
  "packages/*",
  "services/*",
  "apps/*"
]

This configuration tells Yarn to manage dependencies and scripts for packages found in any subdirectory of packages, services, or apps.

After Configuration

Once you've added the workspaces array to your root package.json, navigating to the root of your project in the terminal and running yarn install will leverage the workspace feature. Yarn will install dependencies for all workspaces together, potentially hoisting common dependencies to the root node_modules directory, which can save disk space and improve installation times.

Setting up the workspaces array is the core action required to activate and utilize the Yarn Workspaces feature in your project.