Skip to content

the21st/yarn-2-workspaces-monorepo-example

 
 

Repository files navigation

Yarn 2 workspaces monorepo example

This project demonstrates how to set up a monorepo with Yarn 2.

You can either:

  • clone the repository or
  • set the project up from scratch

1. Cloning the repo

In your work directory, run:

git clone https://github.com/marqetintl/yarn-2-workspaces-monorepo-example.git

Install the required dependencies:

cd yarn-2-workspaces-monorepo-example
yarn

Jump to step 3

2. Setup from scratch

Always refer to the original documentation to get the latest instructions on how to install Yarn.

  1. Install Yarn globally, if you haven't:
npm install -g yarn
  1. Create project folder:
mkdir yarn-2-workspaces-monorepo-example && cd $_
  1. Set Yarn version to latest:
yarn set version berry
yarn set version latest
  1. Initialize project:
yarn init -w

If I were to run tree -a -L 1 , the folder tree would look like this:

.
├── .editorconfig
├── .git
├── .gitattributes
├── .gitignore
├── .yarn
├── .yarnrc.yml
├── README.md
├── package.json
├── packages
└── yarn.lock
  1. Add two packages myapp-1 and myapp-2 to our monorepo:
cd packages/
mkdir myapp-1 myapp-2
  1. Navigate to packages/myapp-2/ and add an index.js file:
cd myapp-2/
yarn init -yp
touch index.js
  1. Update packages/myapp-2/index.js:
const defaultName = "Michaël";

module.exports = {
    defaultName,
    logName(name) {
        return console.log(`Hello! I am ${name}`);
    },
};
  1. Update packages/myapp-2/package.json:
{
    "name": "@miq/myapp-2",
    "main": "index.js"
}
  1. Navigate to packages/myapp-1 and add an index.js file:
cd ../myapp-1/
yarn init -yp
touch index.js
  1. Update packages/myapp-1/index.js:
const { defaultName, logName } = require("@miq/myapp-2");

logName(defaultName);
logName("Jean-Michel");
  1. Then update packages/myapp-1/package.json:
{
    "name": "@miq/myapp-1",
    "dependencies": {
        "@miq/myapp-2": "workspace:*"
    },
    "scripts": {
        "start": "node ."
    }
}
  1. Update the project's package.json:
{
    "name": "@miq/yarn-2-workspaces-monorepo-example",
    "private": true,
    "workspaces": ["packages/*"],
    "scripts": {
        "start:myapp1": "yarn workspace @miq/myapp-1 start"
    }
}
  1. From the root folder, run yarn to install the dependencies:
cd ../../
yarn

3. To run the project

yarn start:myapp1

You should see the output:

...

Hello! I am Michaël
Hello! I am Jean-Michel

...

4. Good to know

  • List all workspaces:
yarn workspaces list
  • Create a new private package and define it as a workspace root with a packages/ directory:
yarn init -w
  • Initialize a private package in the local directory:
yarn init -p

About

How to set up a basic monorepo with Yarn 2 workspaces

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%