Using Lerna to manage JS Monorepos

Kelvin Kitika
The Andela Way
Published in
2 min readJun 25, 2019
Photo by Kevin Ku on Unsplash

In most Full Stack Javascript projects, you will find that during development, the frontend and the backend of the application are managed in different repositories. This is okay at first, but it becomes very difficult to manage as the application grows. The disadvantages include:

  • Installing similar packages on each application
  • Running similar commands separately.

Lerna helps to solve this by allowing easy management of multiple JS applications/ repositories by:

  • Allowing sharing of common packages across all applications
  • Allowing sharing of commands across all applications

Let’s look at an example

Example

To get started, we need to install Lerna

$ npm install --global lerna

Next, create a folder for the Lerna packages

$ mkdir lerna-example && cd lerna-example

To initialize Lerna:

$ lerna init

The folder structure will look like this

lerna-example/
packages/
package.json
lerna.json

We can now add our applications in the packages folder to look something like this.

packages/
front-end/
package.json
backend/
package.json

In order to link common packages within the two applications we just created, we will need to add a script command on the outmost package.json

"scripts": {
"bootstrap": "lerna bootstrap"
}

By running the bootstrap command, Lerna will install the dependencies listed in both applications and link any cross-dependencies. It is the same as running yarn install on each of the applications, but instead, Lerna links packages that are dependencies of each other.

For the second part, we need to start both applications with one command. To do this, we will add an npm script on each application for starting.

backend

"scripts": {
"start": "react-scripts start"
}

front-end

"scripts": {
"start": "node app.js"
}

On our parent package.json we will need to include a start script too.

"scripts": {
"start": "lerna run start"
}

By using lerna run Lerna will look at each package's package.json file for an npm script that matches the script and runs it. It is that simple.

For more information, checkout Lerna on GitHub

--

--