How to set up Lerna with Yarn workspaces


This post goes over how to set up a Lerna monorepo with Yarn workspaces.

Lerna

Create a new Lerna monorepo with lerna init:

npx lerna init

Initialized Lerna files should look like:

tree
.
├── lerna.json
├── package.json
└── packages

1 directory, 2 files

Optional: To enable independent versioning mode in lerna.json:

 {
   "packages": ["packages/*"],
-  "version": "0.0.0"
+  "version": "independent"
 }

Yarn

Enable Yarn workspaces in package.json:

 {
   "name": "root",
   "private": true,
+  "workspaces": ["packages/*"],
   "devDependencies": {
     "lerna": "^4.0.0"
   }
 }

Then add npmClient and useWorkspaces to lerna.json:

 {
+  "npmClient": "yarn",
+  "useWorkspaces": true,
   "packages": ["packages/*"],
   "version": "independent"
 }

Now when you run yarn install, Yarn bootstraps and hoists node modules to the project root directory:

yarn

This means that devDependencies shared across packages can be saved to the project root package.json:

yarn add --dev eslint -W

Resources

Check out the example repository lerna-template.



Please support this site and join our Discord!