Sharing Code with Yarn Workspaces

September 02, 2021

Yarn Logo

Sharing Code with Yarn Workspaces

Recently I was starting a new project that would require a web app, as well as a mobile app. I decided I would use React (Next.js) for the web app and would create a React Native project for the mobile app. One of the first questions I had was how can I limit the amount of code I need to reuse? After searching a bit I stumbled upon Yarn Workspaces. Yarn describes workspaces like so.

The Yarn workspaces aim to make working with monorepos easy, solving one of the main use cases for yarn link in a more declarative way. In short, they allow multiple of your projects to live together in the same repository AND to cross-reference each other - any modification to one’s source code being instantly applied to the others.

This sounds like exactly what I want. I can have three projects. One for the web, one for the app, and a common library that contains code that I can share between the two.

├── package.json
├── packages
│   ├── app
│   │   └── package.json
│   └── common
│   │    └── package.json
│   └── web
│       └── package.json
└── yarn.lock

Let’s set it up!

Create a New Project with Yarn Workspaces

First I will create a new directory that will house the monorepo.

$ mkdir my-new-app

Since yarn workspaces are a feature of yarn version 2 we need to set the proper yarn version for our project.

$ yarn set version berry

Next, we need to initialize our monorepo workspaces

$ yarn init -w

We have now generated a package.json at the root level, as well as generated a packages folder, where Yarn will now expect our various apps to be.

Next, we can yarn init -y inside each app to finish the initial setup, and we can run yarn workspaces list to verify that all of our apps are being picked up.

Now we can scaffold each app any way we want and can reference code inside of the /packages/common directory by running this command at the root of your application.

$ yarn workspace web add common

NOTE: I ran into an error here that was caused by the common package not having a version. After adding a version I was able to add common to both web and app.

How you can structure the code in common however you see fit and reference that code in both the mobile app as well as the web app.

Profile picture

A tech focused blog by Tyler Polito.

© 2021,