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



mkdir yarn-workspaces-sample && cd yarn-workspaces-sample && touch package.json
// package.json
{
    "private": true,
    "workspaces": [
        "packages/*"
    ]
}
mkdir packages && mkdir packages/server && mkdir packages/utils
cd packages/utils && yarn init -y
cd ../server && yarn init -y
cd ../utils && touch main.js
// packages/utils/main.js
function greeting(name) {
    console.log(`Hello, ${name}`);
}

module.exports = {
    greeting
};
cd ../server && touch main.js
// packages/server/main.js

const { greeting } = require('utils');

greeting('Max');

// packages/utils/package.json
{
  "name": "utils",
  "version": "1.0.0",
  "main": "main.js", // index.js ==> main.js
  "license": "MIT"
}
// packages/server/package.json
{
  // ...
  "dependencies": {
    "utils": "1.0.0"
  }
}
yarn install

yarn install will link dependency utils to server

After installing let's check that server has workspace dependency utils:

yarn workspaces info

should print this:

{
  "server": {
    "location": "packages/server",
    "workspaceDependencies": [
      "utils"
    ],
    "mismatchedWorkspaceDependencies": []
  },
  "utils": {
    "location": "packages/utils",
    "workspaceDependencies": [],
    "mismatchedWorkspaceDependencies": []
  }
}

Add scripts

// packages/server/package.json
{
  // ...
  "scripts": {
    "dev": "node main.js"
  }
}
// /package.json (root)
{
    "scripts": {
        "server:dev": "yarn workspace server dev"
    }
}
Share:

About

My name is Max, also known as @mxkvl.

I am a software developer, currently working mostly with TypeScript, React and Node ecosystems.

I write a blog about topics that interest me most: programming languages in general, TypeScript, testing, writing and other great stuff.

Join the Mailing List