Yarn
Yarn is a package manager for JavaScript and TypeScript. It is a alternative to npm
Links
Workspaces
Yarn provide a solution to manage Monorepo - Yarn Workspaces
- Basically a Monorepo manager
- in comparison with Lerna.js Yarn Workspaces are low-level
Setup from scratch
1
| mkdir yarn-workspaces-sample && cd yarn-workspaces-sample && touch package.json
|
1
2
3
4
5
| // package.json
{
"private": true,
"workspaces": ["packages/*"]
}
|
1
| mkdir packages && mkdir packages/server && mkdir packages/utils
|
1
2
| cd packages/utils && yarn init -y
cd ../server && yarn init -y
|
1
| cd ../utils && touch main.js
|
1
2
3
4
5
6
7
8
| // packages/utils/main.js
function greeting(name) {
console.log(`Hello, ${name}`);
}
module.exports = {
greeting,
};
|
1
| cd ../server && touch main.js
|
1
2
3
4
5
| // packages/server/main.js
const { greeting } = require("utils");
greeting("byte");
|
1
2
3
4
5
6
7
| // packages/utils/package.json
{
"name": "utils",
"version": "1.0.0",
"main": "main.js", // index.js ==> main.js
"license": "MIT"
}
|
1
2
3
4
5
6
7
| // packages/server/package.json
{
// ...
"dependencies": {
"utils": "1.0.0"
}
}
|
yarn install will link dependency utils to server
After installing let’s check that server has workspace dependency utils:
should print this:
1
2
3
4
5
6
7
8
9
10
11
12
| {
"server": {
"location": "packages/server",
"workspaceDependencies": ["utils"],
"mismatchedWorkspaceDependencies": []
},
"utils": {
"location": "packages/utils",
"workspaceDependencies": [],
"mismatchedWorkspaceDependencies": []
}
}
|
Add scripts
1
2
3
4
5
6
7
| // packages/server/package.json
{
// ...
"scripts": {
"dev": "node main.js"
}
}
|
1
2
3
4
5
6
| // /package.json (root)
{
"scripts": {
"server:dev": "yarn workspace server dev"
}
}
|