npm workspaces and monorepos

Intermediate · 13 min

One repo, many packages. How npm workspaces link local packages, hoist dependencies and run scripts, compared with pnpm and yarn, and what Turborepo and Nx add.

Before thisnpm scripts and lifecycle hooks

Concise Developer · 13 min

npm workspaces and monorepos

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Concise DeveloperReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A monorepo holds several packages in one repository. npm workspaces (the `workspaces` field in the root `package.json`) let `npm install` treat them as one project: a single lockfile, shared installs and local packages linked to each other.
  • Workspace packages are symlinked into the root `node_modules`, so `require('@scope/core')` in one package resolves to the live source folder of another. Edit `core` and `app` sees the change, with no publishing step.
  • Shared dependencies are hoisted to the root `node_modules`, so one copy serves every package. Conflicting versions are kept nested in the package that needs them.
  • Run commands with `npm run <script> --workspaces --if-present` for all packages, or `-w <name>` for one. npm does not understand which packages depend on which when ordering or caching, which is the gap Turborepo and Nx fill.
  • pnpm and Yarn have workspaces too. pnpm's differ mainly by a stricter, symlinked `node_modules` that stops code importing packages it never declared, and by the `workspace:` version protocol.

The problem: packages that change together

Say you maintain an API service and a library of validation rules it uses. As separate repositories, a change to the library needs a version bump, a publish, and an update in the service before you can even test it together. That is slow and discourages small changes. Putting both in one repository, a monorepo, lets one commit change the library and the service, and one test run check both.

The cost is that your tooling must now understand “many packages in one place”. npm’s answer is workspaces.

Setting one up

A root package.json lists the folders that contain packages:

{
  "name": "mono",
  "private": true,
  "workspaces": ["packages/*"]
}

Each folder under packages/ is a normal package with its own package.json. Here packages/core exports an add function, and packages/app depends on it:

{
  "name": "@mono/app",
  "version": "1.0.0",
  "dependencies": { "@mono/core": "*" }
}

Run npm install once at the root. npm sees that @mono/core is one of your workspaces and does not look for it on the registry. Instead it creates a symbolic link:

node_modules/@mono/app  -> ../../packages/app
node_modules/@mono/core -> ../../packages/core

In a test on npm 11.20, require('@mono/core') from packages/app ran the live source in packages/core and printed app says 42. There is one lockfile at the root, and npm ls shows the app depending on core “deduped” to the local link. This is the main win: edit core, run app, and the change is there immediately.

The root is usually marked private: true because it is only a container and must never be published by accident.

Hoisting

When two packages depend on lodash@4, npm installs one copy in the root node_modules, and both packages find it by walking up directories (the algorithm from how Node resolves modules). That is hoisting. If package A needs lodash@4 and package B needs lodash@3, one version is hoisted and the other is installed nested inside the package that needs it. Disk use and install time both shrink.

Hoisting has a sharp edge: app can require('lodash') without listing it, because it happens to be hoisted for someone else. It works until that other package changes, then breaks. These are called phantom dependencies.

Running scripts

npm run test --workspaces --if-present       # every workspace with a "test" script
npm run start --workspace=@mono/app          # a single workspace (-w also works)
npm install lodash -w @mono/core              # add a dependency to one package

In the test repo, the first command ran app tests, then core tests, in the order the workspaces were found. --if-present skips packages that have no such script. Scripts themselves are covered in npm scripts and lifecycle hooks.

What npm workspaces do not do

npm links packages and runs a script wherever it exists. It does not know that app depends on core, so it does not build core first, does not run independent tasks in parallel, and does not remember that nothing changed since the last build. On a repo with three packages that does not matter. On thirty it does.

Turborepo and Nx sit on top of workspaces and add the missing pieces: a task graph derived from the dependency graph, parallel execution, and a cache keyed on the inputs so unchanged packages replay their results instead of rerunning. They are optional add-ons; start without them and add one when your build times justify it.

pnpm and Yarn

Both have workspaces with the same idea and different trade-offs:

  • pnpm keeps one content-addressed store on disk and builds each project’s node_modules from symlinks into it. Only declared dependencies are visible to a package, which eliminates phantom dependencies, and the layout saves a lot of disk. Workspaces are configured in a pnpm-workspace.yaml file, and local dependencies use a workspace:* version so a published package never accidentally points at a registry copy.
  • Yarn supports workspaces and the workspace: protocol too, and in its newer versions can avoid node_modules entirely with Plug’n’Play.

Choosing between them is a team decision; the concepts above carry across. The video below uses npm. Jilles’ pnpm video under “go deeper” shows the same ideas with pnpm.

For TypeScript, a monorepo also needs build ordering between packages: see project references and monorepos.

What the video covers

Concise Developer’s tutorial, from January 2023, is chaptered: a sample project structure, npm init, creating workspaces from the command line, handling internal dependencies, referencing code from another package, running scripts, and installing dependencies in only one package. That is the setup and daily use covered above. Hoisting edge cases, pnpm, Yarn and Turborepo/Nx come from the prose and the linked videos. The npm behaviour was re-checked on npm 11.20 and the video’s workflow is unchanged. No transcript was available.

Where this fits

Workspaces are how a growing Node codebase is organized. Once a package is useful on its own, the next lesson shows how to share it publicly: publishing an npm package.

Check yourself

  1. 01In a workspace, package `@mono/app` lists `"@mono/core": "*"` as a dependency and `@mono/core` is another folder in the repo. After `npm install`, where does `node_modules/@mono/core` point?

    To the local `packages/core` folder, as a symbolic link. npm sees that a workspace with that name exists and links it instead of downloading from the registry, so edits to `core` are visible to `app` immediately.

  2. 02What does `npm run test --workspaces --if-present` do, and why is `--if-present` there?

    It runs the `test` script in every workspace package, in the order the workspaces are listed. `--if-present` makes npm skip packages with no `test` script instead of failing on them.

  3. 03What problem do Turborepo or Nx solve that plain npm workspaces do not?

    They understand the dependency graph between packages, so they run tasks in the right order, in parallel where possible, and cache results so unchanged packages are not rebuilt. npm workspaces only link packages and run a script wherever it exists.

  4. 04Why might code that works in an npm workspace fail under pnpm?

    npm hoists dependencies to the root, so a package can accidentally import something it never listed in its own `package.json` and still work. pnpm's stricter layout only exposes declared dependencies, so the undeclared import fails. The fix is to declare it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark