npm Workspaces
A monorepo keeps several packages in one repository: a library and the app that uses it, or twenty internal packages that release together. Without help, you'd publish the library just to test it in the app. Workspaces let the package manager link local packages into each other and install every package's dependencies in one go, with one lockfile.
npm, Yarn and pnpm all have workspaces with the same core idea; this lesson uses npm, and the Yarn and pnpm lessons show their extras.
Setting up
The root package.json lists where the packages live; it is private, because the root itself is never published:
{
"name": "acme",
"private": true,
"workspaces": ["packages/*"]
}mkdir -p acme/packages/{format,cli} && cd acme
echo '{ "name": "acme", "private": true, "workspaces": ["packages/*"] }' > package.json
cat > packages/format/package.json <<'JSON'
{ "name": "@acme/format", "version": "1.0.0", "main": "index.js",
"dependencies": { "ms": "^2.1.3" },
"scripts": { "test": "node -e \"require('./').duration(90000) === '2m' || process.exit(1)\" && echo format ok" } }
JSON
echo 'const ms = require("ms"); exports.duration = (n) => ms(n);' > packages/format/index.js
cat > packages/cli/package.json <<'JSON'
{ "name": "@acme/cli", "version": "1.0.0",
"dependencies": { "@acme/format": "^1.0.0" },
"scripts": { "start": "node index.js" } }
JSON
echo 'console.log("took", require("@acme/format").duration(90000));' > packages/cli/index.js
npm install 2>&1 | grep added
for l in node_modules/@acme/*; do echo "$l -> $(readlink $l)"; done
ls node_modules
ls -d packages/*/node_modules 2>/dev/null || echo "(no node_modules inside the packages)"
npm run start -w @acme/cliadded 3 packages in 487ms
node_modules/@acme/cli -> ../../packages/cli
node_modules/@acme/format -> ../../packages/format
@acme
ms
(no node_modules inside the packages)
> @acme/cli@1.0.0 start
> node index.js
took 2m
What npm install at the root did:
- created symlinks
node_modules/@acme/format -> ../../packages/format, sorequire('@acme/format')from the CLI resolves to the live source: edit it and the CLI sees the change, no publish needed; - hoisted
ms(needed byformat) into the rootnode_modules, shared by everyone; - wrote a single
package-lock.jsonat the root. The packages have no lockfiles and nonode_modulesof their own unless versions conflict.
Running commands across workspaces
-w <name> (--workspace) targets one workspace (repeatable), --workspaces targets all (npm 11 warns that the old short form -ws will be removed), and --if-present skips packages that don't have the script:
mkdir -p acme/packages/{format,cli} && cd acme
echo '{ "name": "acme", "private": true, "workspaces": ["packages/*"] }' > package.json
echo '{ "name": "@acme/format", "version": "1.0.0", "scripts": { "test": "echo testing format", "build": "echo building format" } }' > packages/format/package.json
echo '{ "name": "@acme/cli", "version": "1.0.0", "dependencies": { "@acme/format": "^1.0.0" }, "scripts": { "build": "echo building cli" } }' > packages/cli/package.json
npm install > /dev/null 2>&1
npm run build --workspaces
echo "---"
npm test --workspaces --if-present
echo "---"
npm install left-pad@1.3.0 -w @acme/format 2>&1 | grep -v deprecated
npm pkg get dependencies -w @acme/format
npm ls --all
> @acme/cli@1.0.0 build
> echo building cli
building cli
> @acme/format@1.0.0 build
> echo building format
building format
---
> @acme/format@1.0.0 test
> echo testing format
testing format
---
added 1 package in 469ms
{
"@acme/format": {
"left-pad": "^1.3.0"
}
}
acme@ /home/learner/acme
├─┬ @acme/cli@1.0.0 -> ./packages/cli
│ └── @acme/format@1.0.0 deduped -> ./packages/format
└─┬ @acme/format@1.0.0 -> ./packages/format
└── left-pad@1.3.0
Two things to notice:
npm run build --workspacesran the packages in the order they appear on disk (alphabetical here:clibeforeformat), not dependency order. npm doesn't know thatclineedsformatbuilt first. pnpm's-rand Yarn'sforeach --topologicaldo, and that is one reason larger monorepos pick them (or Turborepo/Nx).npm install x -w pkgadds the dependency to that package'spackage.json, while the files still go into the shared rootnode_modules.
Hoisting is a double-edged sword
Hoisting saves disk and install time, but every package can now require whatever any other package depends on. @acme/cli never declared ms, yet this works:
mkdir -p acme/packages/{format,cli} && cd acme
echo '{ "name": "acme", "private": true, "workspaces": ["packages/*"] }' > package.json
echo '{ "name": "@acme/format", "version": "1.0.0", "dependencies": { "ms": "^2.1.3" } }' > packages/format/package.json
echo '{ "name": "@acme/cli", "version": "1.0.0" }' > packages/cli/package.json
echo 'console.log("cli found ms:", require("ms")(60000));' > packages/cli/index.js
npm install > /dev/null 2>&1
node packages/cli/index.jscli found ms: 1m
It works in the monorepo and breaks for anyone who installs @acme/cli from the registry. That's a phantom dependency, and pnpm makes it an error.
Test yourself
How does require('@acme/format') in packages/cli find the local package?
- npm copies it into packages/cli/node_modules
- npm creates a symlink in the root node_modules pointing to packages/format
- Node reads the workspaces field
- It is published to the registry first
In what order does npm run build --workspaces run the workspaces?
- Dependency (topological) order
- The order they are found on disk / listed
- In parallel
- Alphabetical by version
How many lockfiles does an npm workspace monorepo have?
- One per package
- One at the root
- None
- One per dependency