Monorepo
PNPM
JavaScript
Node.js

Monorepo with PNPM workspace

4 min read
Anas Rin

Monorepo ?

Monorepo is single repository with many project or packages (library or modules), you can reuse code as package.

en.wikipedia.org/wiki/Monorepo has good explaination for Monorepo including advantages and disadvantages.

repoappsapp 1app 2pkgslib 1lib 2lib 3

Monorepo with PNPM workspace

PNPM only need pnpm-workspace.yaml on your root repository alongside packages.json, with array path to directory in packages property.

1
packages:
2
- "apps/*" # support glob pattern
3
- "packages/*"
monorepo-example/
├─ apps/
├─ packages/
├─ package.json
└─ pnpm-workspace.yaml

NOTE: apps/* and packages/* is very popular monorepo structure, where apps/* is projects directory and packages/* is reusable code.

All you need just create directory inside packages list, change directory to it, and do pnpm init.

mkdir -p packages/math-lib
cd packages/math-lib
pnpm init
cd ../..
mkdir -p apps/calculator
cd apps/calculator
pnpm init
cd ../..

List all workspaces

List all workspaces in JSON format.

pnpm m ls --depth -1 --json

Command specific workspace

Run command on specific workspace using flag --filter following with name in package.json.

# Format
pnpm --filter <workspace> <command>
pnpm -F <workspace> <command> # short alias
# Example
pnpm --filter math-lib add lodash
pnpm --filter math-lib add -D typescript @types/lodash
pnpm --filter calculator run test
# Support glob pattern
pnpm --filter pkg* run test

NOTE: PNPM use name property in package.json to filter workspace, so make sure ever name in package.json is unique.

Add local dependency

Add local dependency using flag --workspace to only adds the new dependency if it is found in the workspace.

# Example
pnpm --filter calculator add math-lib --workspace

Project example

mkdir -p monorepo-example
cd monorepo-example
pnpm init
mkdir -p packages/math-lib
cd packages/math-lib
pnpm init
cd ../..
mkdir -p apps/calculator
cd apps/calculator
pnpm init
cd ../..
touch packages/math-lib/index.js
touch apps/calculator/index.js
1
const add = (a, b) => a + b;
2
const subtract = (a, b) => a - b;
3
4
module.exports = {
5
add,
6
subtract,
7
};
1
const { add, subtract } = require("math-lib");
2
3
console.log(`9 + 10 = ${add(9, 10)}`);
4
console.log(`26 - 9 = ${subtract(26, 9)}`);
pnpm --filter calculator add math-lib --workspace
1
{
2
"scripts": {
3
"start": "node index.js"
4
}
5
}
1
{
2
"scripts": {
3
"calculator:start": "pnpm -F calculator run start"
4
}
5
}
pnpm run calculator:start
output calculator run start