If you're tired of jumping from repository to repository just to update a single shared function, this guide is for you. Today, we're going to build a robust Monorepo foundation using the power of Lerna and the efficiency of Yarn Workspaces.
Why is this duo unbeatable? π€
Before we dive into the code, let's look at the "why":
Yarn Workspaces: Handles the heavy lifting of dependencies. It prevents duplication and ensures your internal packages communicate seamlessly.
Lerna: Acts as the conductor. It makes it easy to run commands in bulk (like running tests across 10 packages at once) and manages versioning for publishing.
Step-by-Step: From Zero to Monorepo
1. Preparing the Ground
Create your project folder and initialize Git:
mkdir my-monorepo && cd my-monorepo
git init
yarn init -y
2. Activating Yarn Workspaces
Open your package.json and add the lines below. This is crucial to tell Yarn where your sub-projects will live:
{
"name": "my-monorepo",
"private": true,
"workspaces": [
"packages/*"
]
}
Note: We set
"private": truebecause the root repository itself should not be published to NPM.
3. Initializing Lerna
With Yarn ready, let's bring in Lerna to manage the workflow:
npm install --global lerna
lerna init
This will create a lerna.json file---the brain of our orchestration.
4. Creating Your First Packages
Let's set up a structure with two example packages:
mkdir packages
mkdir packages/api packages/web-app
# Initializing each one
cd packages/api && yarn init -y
cd ../web-app && yarn init -y
Managing Dependencies Like a Pro π
This is where the magic happens. With Yarn Workspaces, you don't need to enter each folder to install something.
-
Common Dependency (across all packages):
yarn add lodash -W -
Specific Dependency (only for one package):
# Adding React only to the web-app workspace web-app yarn add react
The Power of Single Commands with Lerna
Imagine you have 5 packages, and all of them have a test script in their package.json. Instead of running them one by one, simply use:
lerna run test
Lerna will traverse every folder inside packages/ and execute the test in each one. Pure productivity!
π‘ Best Practices to Keep You on Track
Organization is Everything: Keep naming clear. For example:
@my-project/ui,@my-project/utils.Document the Root: Maintain a
README.mdin the root explaining how to run the entire project.Automation: Set up a CI (like GitHub Actions) to run
lerna run buildwhenever a new Pull Request is opened.
Conclusion
Setting up a monorepo with Lerna + Yarn Workspaces is the first step toward scaling software engineering projects with quality. You gain consistency, reuse code efficiently, and stop fighting package management.
Want to dive deeper?
Did you find this tutorial helpful? Do you have any questions about the setup? Let's talk in the comments below! π
Top comments (0)