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
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
Always refer to the original documentation to get the latest instructions on how to install Yarn.
- Install Yarn globally, if you haven't:
npm install -g yarn
- Create project folder:
mkdir yarn-2-workspaces-monorepo-example && cd $_
- Set Yarn version to latest:
yarn set version berry
yarn set version latest
- 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
- Add two packages
myapp-1
andmyapp-2
to our monorepo:
cd packages/
mkdir myapp-1 myapp-2
- Navigate to
packages/myapp-2/
and add anindex.js
file:
cd myapp-2/
yarn init -yp
touch index.js
- Update
packages/myapp-2/index.js
:
const defaultName = "Michaël";
module.exports = {
defaultName,
logName(name) {
return console.log(`Hello! I am ${name}`);
},
};
- Update
packages/myapp-2/package.json
:
{
"name": "@miq/myapp-2",
"main": "index.js"
}
- Navigate to
packages/myapp-1
and add anindex.js
file:
cd ../myapp-1/
yarn init -yp
touch index.js
- Update
packages/myapp-1/index.js
:
const { defaultName, logName } = require("@miq/myapp-2");
logName(defaultName);
logName("Jean-Michel");
- Then update
packages/myapp-1/package.json
:
{
"name": "@miq/myapp-1",
"dependencies": {
"@miq/myapp-2": "workspace:*"
},
"scripts": {
"start": "node ."
}
}
- 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"
}
}
- From the root folder, run
yarn
to install the dependencies:
cd ../../
yarn
yarn start:myapp1
You should see the output:
...
Hello! I am Michaël
Hello! I am Jean-Michel
...
- 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