Blog>
Snippets

Monorepo Dependency Management with Yarn Workspaces

Showcasing how to use Yarn Workspaces to manage node dependencies in a unified manner across all the packages in the Angular monorepo.
// Define workspace in your package.json in the Angular monorepo root
{
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "build": "yarn workspaces run build",
    "test": "yarn workspaces run test"
  },
  "dependencies": {
    "shared-dep": "^1.0.0"
  }
}
This block of code serves as the primary workspace configuration in the `package.json` file at the root of the Angular monorepo. It defines the use of Yarn Workspaces with a wildcard pattern to include all package directories under a `packages` folder. It marks the project as private to prevent accidental publication. It includes workspace-wide scripts to build and test all packages. It also shows an example of how to add a dependency that is shared across all workspaces.
// Add a new dependency to all workspaces
$ yarn workspace @your-monorepo-name/package-a add lodash
This snippet is a command-line instruction for adding a new dependency (lodash, in this case) to a specific package within the monorepo. Replace `@your-monorepo-name/package-a` with the actual name of your package. Yarn will manage this dependency in the context of the workspace, ensuring that it is installed in the correct location and that versions are managed consistently across the monorepo.
// Install all workspace dependencies from the root
$ yarn install
This command is run in the root directory of the monorepo to install all dependencies for all workspaces. Yarn Workspaces takes care of linking shared dependencies and making them available across all packages, optimizing installation times and disk space usage.