Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 133 ยท Compression, CLI and Tooling

npm Workspaces and Monorepos

Organize several Node.js packages in one repository with npm workspaces - layout, linking, running scripts, shared code, semver ranges, release planning and when to add Turborepo or Nx.

Sooner or later a project outgrows a single package.json. You have a web app, an API, a command-line tool and a few helpers they all share, such as validation rules or a configuration loader. You can put each one in its own Git repository, but then a change to the shared code means publishing a new version, bumping it in three other repositories, and waiting for four pipelines. Or you can put everything in one repository: a monorepo.

Since version 7, npm has built-in support for this layout, called workspaces. One repository holds many packages; one npm install at the root installs and links them all; and a package can depend on a sibling by name, as if it had been published, while the code on disk is always the latest. This lesson shows the layout, the commands and the daily workflow, then builds two small tools that explain what monorepo tooling does for you: ordering builds by dependency, and planning versions.

Workspace commands here are read-only examples for your own machine, because the editor on this site cannot install packages or create folders of projects. The runnable examples model the logic with plain Node.js.

The layout

A typical monorepo has a root package.json that is itself not a package you publish (it is "private": true) and a folder of packages:

TEXT
my-project/
  package.json              (root: lists the workspaces)
  package-lock.json         (one lock file for everything)
  packages/
    config/
      package.json          ("@acme/config")
      index.js
    utils/
      package.json          ("@acme/utils", depends on @acme/config)
      index.js
  apps/
    api/
      package.json          ("@acme/api", depends on @acme/utils)
      server.js
    web/
      package.json          ("@acme/web", depends on @acme/utils)

The root manifest declares where the workspaces live:

JSON
{
  "name": "acme-monorepo",
  "private": true,
  "workspaces": ["packages/*", "apps/*"],
  "scripts": {
    "build": "npm run build --workspaces --if-present",
    "test": "npm test --workspaces --if-present"
  }
}

Every folder that matches a pattern and contains a package.json is a workspace. Give your packages a scope (@acme/) so their names cannot clash with public packages on the registry. Inside a package, the manifest looks like any other:

JSON
{
  "name": "@acme/utils",
  "version": "1.2.0",
  "type": "module",
  "exports": "./index.js",
  "dependencies": {
    "@acme/config": "^1.0.0"
  }
}

(See package.json Explained for every field, and Creating and Publishing Packages for exports.)

What npm install does

Run npm install once at the root. npm reads all workspace manifests, resolves their external dependencies into one tree, and, for each dependency that is also a workspace, creates a symbolic link in the root node_modules.

flowchart TD
    R["Root<br/>package.json + package-lock.json"] --> NM["node_modules/"]
    NM --> E["express, react, ... (shared, hoisted)"]
    NM --> L1["@acme/utils (symlink)"]
    NM --> L2["@acme/config (symlink)"]
    L1 -.-> P1["packages/utils/"]
    L2 -.-> P2["packages/config/"]
    P1 --> API["apps/api imports '@acme/utils'"]

Workspace packages appear in node_modules as links to the real folders, so an import by name always loads the current source.

Two consequences are worth remembering. First, import { slugify } from '@acme/utils' works from any workspace and always sees your latest edits; there is nothing to publish or copy. Second, dependencies are hoisted to the root node_modules when versions allow, which saves disk space and install time, but means a package can accidentally import something it never declared in its own package.json. That works on your machine and breaks when the package is used elsewhere. Keep each package's dependencies honest.

npm has no special workspace: version syntax (pnpm and Yarn do). In npm you write an ordinary range such as "^1.0.0"; if the local workspace's version satisfies that range, npm links it, otherwise it would try to download that version from the registry. This is why version numbers in a workspace matter, and why the later sections on semver are not academic.

Everyday commands

Terminal
# read-only: run in the monorepo root

# install everything and link the workspaces
npm install

# add an external dependency to ONE workspace
npm install zod --workspace=@acme/api          # short form: -w @acme/api

# add a sibling as a dependency (npm links it because the range is satisfied)
npm install @acme/utils --workspace=@acme/web

# run a script in one workspace, or in all that have it
npm run build --workspace=@acme/utils
npm run build --workspaces --if-present

# run any command inside a workspace folder
npm exec --workspace=@acme/api -- node --version

# create a new package with a basic manifest
npm init -w packages/logger

# see the tree
npm ls @acme/utils

Always use --if-present when running a script over all workspaces; without it, npm fails at the first package that lacks the script. Note that --workspaces runs workspaces in the order they are listed, not in dependency order. If @acme/web needs @acme/utils to be built first and the listing puts web earlier, the build fails. Dedicated tools (below) compute the correct order; with plain npm you list workspaces in a safe order or call scripts explicitly.

Sharing code between packages

The usual shape is a few library packages (shared logic, types, configuration) and several applications that consume them.

  • Keep libraries small and focused: @acme/config, @acme/utils, @acme/ui.
  • Libraries should not import from applications, and should avoid importing from each other in circles. Dependencies point one way, "down" towards the base.
  • If a package needs a build step (TypeScript, bundling), its exports should point at the built output, and the root build must run before its consumers. Packages written in plain modern JavaScript can export their source directly and need no build at all.
  • Share tooling configuration (ESLint, TypeScript base config, test setup) as packages too, so that rules change in one place.

Why order matters: a dependency graph

Consider a small repository: config has no dependencies, utils needs config, ui needs utils, api needs utils and config, and web needs ui and api. Packages that do not depend on each other can be built in parallel, but a package can only be built after everything it depends on. The ordering problem is a topological sort, and a cycle (A needs B needs A) has no valid order at all.

flowchart BT
    config["@acme/config"]
    utils["@acme/utils"] --> config
    ui["@acme/ui"] --> utils
    api["@acme/api"] --> utils
    api --> config
    web["@acme/web"] --> ui
    web --> api

Arrows point from a package to the packages it needs. config must be built first, web last.

This is exactly what Turborepo, Nx, pnpm and Lerna compute. The code below does the same job in about 30 lines: it ignores external dependencies, groups packages into build levels that can run in parallel, finds which packages are affected by a change, and detects cycles.

Node.js Build order, affected packages and cycles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The "affected" idea is why monorepo tools are fast: on a pull request that touches only @acme/ui, CI rebuilds and tests ui and web and skips config, utils and api. The cycle error is the reason to keep your dependency arrows pointing one way.

Versions and semver

Packages that are never published (internal applications) can keep any version. Libraries that are published, or that others consume, follow semantic versioning: MAJOR.MINOR.PATCH. Increase PATCH for bug fixes, MINOR for backward-compatible features, MAJOR for breaking changes. Consumers express what they accept with a range:

Range Accepts Notes
1.2.3 exactly 1.2.3 Pinned
^1.2.3 >=1.2.3 <2.0.0 The default when you run npm install; allows minor and patch updates
^0.5.0 >=0.5.0 <0.6.0 For 0.x versions, the caret treats the minor as breaking
~1.2.3 >=1.2.3 <1.3.0 Only patch updates
* anything Avoid, except for internal packages you always link

In a workspace, this matters in a concrete way. When @acme/utils goes from 1.2.0 to 2.0.0, the range ^1.0.0 in @acme/api no longer accepts it, so npm would stop linking the local folder and look for version 1.x on the registry, or fail. A major bump therefore has to be accompanied by updating every dependent's range, and those dependents in turn need new versions of their own. Doing this by hand across ten packages is where mistakes creep in.

Release workflows. Tools such as Changesets and Lerna handle this. Developers write a small note with each pull request ("@acme/utils minor: added slugify"); at release time the tool bumps versions, rewrites dependent ranges, updates changelogs and publishes in dependency order. With plain npm you can do the steps yourself: npm version minor --workspace=@acme/utils and npm publish --workspace=@acme/utils. Packages published with a scope need --access public the first time.

The example below implements the heart of that planning step. It includes a small semver range checker (npm itself uses the semver package) and answers the question: "I am releasing this version of a package; which dependents must change and be released too?"

Node.js A release planner with semver ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A minor release of utils touches nobody else, because ^1.0.0 and ^1.1.0 accept 1.3.0. A major release forces ui and api to adopt it, which produces new patch versions of those two. Those new versions still satisfy the ranges that web uses, so the chain stops there. For ui, a minor bump (0.6.0) breaks web's ^0.5.0 range, because the caret is stricter for 0.x versions. These are the cases a release tool saves you from computing by hand.

When plain workspaces are enough, and when they are not

npm workspaces give you linking, hoisting and the -w flags. They do not give you task caching, dependency-ordered execution, or "run only what changed". When a repository gets large:

  • Turborepo and Nx add a task graph, parallel execution, local and remote caching ("this package's inputs did not change, so replay the previous output"), and affected-only runs.
  • pnpm and Yarn offer their own workspace implementations with stricter dependency isolation (a package cannot import what it did not declare) and the workspace: protocol.
  • Changesets or Lerna manage versioning and publishing.

Start with plain npm workspaces. Add a tool when builds become slow or releases become error-prone, not before. Whatever you use, keep one lock file at the root, commit it, and use npm ci in CI for repeatable installs. For deployment, remember that an application in a monorepo still needs only its own dependencies in production; see Deployment and Bundling and Building Node.js Apps.

Common mistakes

  • Forgetting "private": true in the root. Without it you can accidentally publish the root package.
  • Undeclared dependencies. An import that works only because of hoisting. Check each package's manifest, and test packages in isolation in CI.
  • Circular dependencies. They make a build order impossible and often signal that shared code belongs in a third package.
  • Version drift. Two packages using different major versions of the same library can bloat installs or cause subtle bugs; align versions (npm will tell you in npm ls).
  • Running a single package's script from the wrong folder. Use -w, or cd into the package, and be aware that a script run with --workspaces stops at the first failure.
  • Publishing a package whose exports point at files that are not in the published tarball. Use the files field and check with npm pack --dry-run.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the "workspaces" field in the root package.json do?

    Each matching folder with a package.json becomes a workspace. npm installs them together and links them into the root node_modules.
  2. 2. Why should library packages in a monorepo avoid circular dependencies?

    A cycle has no valid topological order. It is also usually a sign that shared code should move into its own package.
  3. 3. @acme/utils is released as 2.0.0. @acme/api depends on it with the range ^1.1.0. What happens in a workspace?

    ^1.1.0 means >=1.1.0 <2.0.0. A new major version is outside it, so the dependent has to adopt the new range (and be released).
  4. 4. Does npm run --workspaces execute scripts in dependency order?

    Plain npm has no task graph. You either list workspaces in a safe order or use a tool that knows the dependencies.
  5. 5. What does ^0.5.0 accept?

    For versions below 1.0.0, a minor bump may be breaking, so the caret only allows patch updates within the same minor.

Summary

  • A monorepo keeps many packages in one repository. In npm, the root package.json lists them under "workspaces" and is private.
  • npm install at the root installs one dependency tree and links workspace packages into node_modules, so imports by name always see the latest source.
  • Use -w <name> to target one workspace, --workspaces --if-present to run scripts everywhere, and remember that plain npm does not order tasks by dependency.
  • Keep dependency arrows one-directional, declare every dependency honestly, and give packages a scope.
  • Version libraries with semver; a major bump forces dependents to update their ranges. Use Changesets or Lerna to plan releases, and Turborepo or Nx when you need caching and affected-only runs.

Next: Express and Minimal Frameworks