Episode 9: Using Yarn Workspace Commands to Simplify Monorepo Management

The Problem with Changing Directories

In a monorepo with multiple products and packages, you often:

  1. Jump between directories to run commands for different packages.

  2. Lose productivity managing these repetitive changes.


Solution: Yarn Workspace Command

Yarn’s workspace command allows you to:

  • Execute scripts or commands for a specific package from any location within the repo.

  • Avoid changing directories manually.

  • Manage dependencies for individual packages with ease.


How to Use Yarn Workspace Commands

Running Scripts for a Specific Package

  1. Directly from the Package Directory
    Navigate to the package directory and run the script:

     cd moduleA
     yarn build
    
  2. From the Root Using yarn workspace
    Run the script from the root (or any directory) with:

     yarn workspace moduleA build
    
    • moduleA: Name of the package as defined in its package.json.

    • build: Script to execute.


Adding Dependencies to a Specific Package

Instead of navigating to the package directory:

  1. Add a dependency:

     yarn workspace moduleA add react
    
  2. Check the package.json of moduleA—React is added to its dependencies.

Removing Dependencies

Use the remove command in the same way:

yarn workspace moduleA remove react

Why This is Useful

  1. Run Commands Anywhere
    Example: Run build for moduleA while inside the directory of moduleB:

     yarn workspace moduleA build
    
  2. Batch Operations
    Run scripts or manage dependencies across multiple packages efficiently.


Practical Example

Step-by-Step Use Case

  1. Define Scripts in moduleA/package.json:

     {
       "scripts": {
         "build": "node index.js",
         "start": "moduleB-script"
       }
     }
    
  2. Run build from Anywhere
    Navigate to the repo root or another module and execute:

     yarn workspace moduleA build
    
  3. Add React to moduleA
    Without changing directories:

     yarn workspace moduleA add react
    

Benefits of Yarn Workspace Commands

  • Saves Time: Avoid unnecessary directory changes.

  • Improves Workflow: Seamlessly run commands and manage dependencies.

  • Monorepo-Friendly: Execute commands across packages in one place.

  • Batch Operations: Combine with scripting to automate repetitive tasks across multiple packages.


Summary

Yarn Workspace commands are a powerful feature for monorepo management. By using yarn workspace, you can:

  • Run scripts for any package from any location.

  • Add or remove dependencies for specific packages.

  • Drastically simplify workflows in large repositories.