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:
Jump between directories to run commands for different packages.
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
Directly from the Package Directory
Navigate to the package directory and run the script:cd moduleA yarn build
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 itspackage.json
.build
: Script to execute.
Adding Dependencies to a Specific Package
Instead of navigating to the package directory:
Add a dependency:
yarn workspace moduleA add react
Check the
package.json
ofmoduleA
—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
Run Commands Anywhere
Example: Runbuild
formoduleA
while inside the directory ofmoduleB
:yarn workspace moduleA build
Batch Operations
Run scripts or manage dependencies across multiple packages efficiently.
Practical Example
Step-by-Step Use Case
Define Scripts in
moduleA/package.json
:{ "scripts": { "build": "node index.js", "start": "moduleB-script" } }
Run
build
from Anywhere
Navigate to the repo root or another module and execute:yarn workspace moduleA build
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.