DEV Community

José Miguel Álvarez Vañó
José Miguel Álvarez Vañó

Posted on • Originally published at jmalvarez.dev

Introduction to Monorepos with Yarn Workspaces

A monorepo is a repository that contains multiple projects inside of it. For example, a monorepo could contain a frontend app and a backend app. Inside the project there could also be shared libraries. In monorepos it is very easy to make changes to multiple projects at one time.

A monorepo is not the same as a monolith. When you make a change in a monorepo you only have to rebuild the projects that are affected by the change. This is an important point because it lets the teams work independently and improve the developer experience. In a monolith everything is released together. In a monorepo you have flexibility to decide when and what to release.

Configure workspaces in your package.json

Yarn Workspaces allows us to setup multiple packages in a single repository.

Start by creating a package.json in the root of the project and adding the following:



{
  "private": true,
  "workspaces": ["project-a", "project-b"]
}


Enter fullscreen mode Exit fullscreen mode

Each project should be listed in the workspaces array.

Then create one subfolder per workspace and add a package.json in those subfolders. Let's add some dependencies to see how Yarn handles it.



{
  "name": "@jmalvarez/project-a",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "4.17.21",
    "@jmalvarez/project-b": "1.0.0"
  }
}


Enter fullscreen mode Exit fullscreen mode


{
  "name": "@jmalvarez/project-b",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "4.17.21"
  }
}


Enter fullscreen mode Exit fullscreen mode

Our setup is ready. Execute now yarn install.

Project structure

As you can see, only one node_modules folder is created to handle all the dependencies. There are no dependencies duplicated. Furthermore, we didn't need to use yarn link to require project-b from project-a.

How to run commands

To add new dependencies, you just have to run the appropriate command inside the project subfolder.



cd project-a
yarn add uuid


Enter fullscreen mode Exit fullscreen mode

Another possibility to run commands from the root folder is using yarn workspace <workspace_name> <command>. For example, to add a new dependency from the root folder we could do the following:



yarn workspace @jmalvarez/project-a add uuid


Enter fullscreen mode Exit fullscreen mode

If we wanted to execute the same command in every workspace we could do it with yarn workspaces run <command>. For example:



yarn workspaces run test

Enter fullscreen mode Exit fullscreen mode




Resources

Top comments (0)