NPM Workspaces: Why Does My Monorepo Build Work Locally but Break in CI?
DEV Community

NPM Workspaces: Why Does My Monorepo Build Work Locally but Break in CI?

One root install, one lockfile, one set of versions, and the build-order trap

It's 6:40 pm. Your pull request is green on your laptop. You push, CI goes red, and the error says Cannot find module '@acme/core'.

You didn't touch that import. Nobody did. You re-run the pipeline anyway, because hope is a strategy, and it fails again.

If you've got two or three packages sharing code in one repo, you've probably met some version of this. NPM workspaces are the built-in way to keep those packages consistent: one install, one lockfile, shared dependency versions, and one command that runs a script everywhere. But the feature has sharp edges that most tutorials skip.

Here's the open question for this article: why did the build pass on your machine and fail on a clean checkout? We'll answer it before the end.

If you like practical monorepo write-ups like this, follow me here on Medium. I post one every week.

By the end you'll know how to set up workspaces, run scripts recursively, filter to the packages you care about, fake parallel runs (npm doesn't do them natively), and avoid the hoisting trap that hides missing dependencies.

What are NPM workspaces, really?

Workspaces let one root package.json manage several packages in the same repository. They landed in npm 7, so any modern Node install has them. Check yours:

npm -v

Before you rely on any flag in this article, skim the official npm workspaces docs for your version. The CLI is still moving.

Before we get into the examples, a quick note: The code snippets provided here are meant purely for understanding the concept. Always refer to the official documentation for the most current API and syntax.

We'll build one small repo and grow it as we go. Two packages: @acme/core (a tiny shared library) and @acme/app (a consumer). Both are TypeScript.

Quick version: the minimum setup

Create this layout:

acme/
  package.json
  tsconfig.base.json
  packages/
    core/
      package.json
      tsconfig.json
      src/index.ts
    app/
      package.json
      tsconfig.json
      src/index.ts
{
  "name": "acme",
  "version": "1.0.0",
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "build": "npm run build --workspaces"
  },
  "devDependencies": {
    "@types/node": "^22.0.0",
    "typescript": "^5.6.0"
  }
}

(Strip the // comment line if you paste these into real JSON files. I'm using it as the file name label.)

Two things matter here. "private": true stops you from accidentally publishing the root. And TypeScript is installed once, at the root, so every package uses the same compiler version. That's the "make things the same" part: one version of the tool, everywhere.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "strict": true,
    "declaration": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}
{
  "name": "@acme/core",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsc"
  }
}
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": [
    "src"
  ]
}
export function formatPrice(cents: number): string {
  return `$${(cents / 100).toFixed(2)}`;
}

Now the consumer:

{
  "name": "@acme/app",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  },
  "dependencies": {
    "@acme/core": "*"
  }
}
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": [
    "src"
  ]
}
import { formatPrice } from "@acme/core";
console.log(formatPrice(1999));

Run one install from the root:

cd acme
npm install
ls -l node_modules/@acme

Expected output (trimmed):

core -> ../../packages/core
app -> ../../packages/app

Those are symlinks. Your workspace packages show up in the root node_modules as links to the real folders, so import "@acme/core" resolves to your local source instead of the registry. Edit core, and the app sees it. No npm link dance.

Real-world version. Notice the "*" range for @acme/core. npm sees that a local workspace satisfies it and links the folder instead of fetching anything. If you pin a version the workspace doesn't match, say ^2.0.0 while core is at 1.0.0, npm will go to the registry and install a copy from there. That's a quiet source of "why is my local change ignored" bugs.

Under the hood. There's a single package-lock.json at the root. Workspaces are treated as link nodes in one dependency tree, which npm's tree builder (Arborist) dedupes and hoists to the root node_modules where it can. One tree, one lockfile, one answer to "which version of this is installed?"

So far everything looks smooth. What happens when you run the build for the whole repo?

What does a recursive call actually do?

The answer to "run this script in every package" is the --workspaces flag, or -ws for short.

Quick version:

npm run build --workspaces

npm walks each workspace and runs its build script. If some packages lack the script, add --if-present so npm skips them instead of failing:

npm run build -ws --if-present

Expected output (trimmed):

> @acme/app@1.0.0 build
> tsc
> @acme/core@1.0.0 build
> tsc

Look at that order. App built before core. Keep that in mind.

Real-world version: the wrong version that still runs. Here's the trap. On your laptop, you already built core yesterday, so packages/core/dist exists. App's tsc finds the old dist/index.d.ts, compiles happily, and the whole thing looks fine.

On a clean CI checkout, dist doesn't exist. App builds first (workspaces from a glob like packages/* typically resolve alphabetically, and app comes before core), and TypeScript can't find the types:

src/index.ts(1,28): error TS2307: Cannot find module '@acme/core' or its corresponding type declarations.

That's the answer to our open question. The recursive flag runs workspaces in the order npm lists them. It does not read your dependency graph. Locally, a stale dist folder was covering for the missing ordering.

The fix is to be explicit about order in the root script:

{
  "scripts": {
    "build": "npm run build -w @acme/core && npm run build -w @acme/app"
  }
}

Now clean checkouts and warm laptops behave the same. To prove it to yourself, delete both dist folders and run npm run build from the root. It should succeed every time.

Have you ever had a build that only worked because of leftover output on your disk? Hold that thought, there's a cousin of it later in the article.

Under the hood. --workspaces is a config switch that tells the command to run in the context of all configured workspaces. Commands that touch the dependency tree (install, update) link workspaces into node_modules. Commands that run things (test, exec, publish) go to the root project unless you pass a workspace flag. That's why a bare npm test at the root doesn't run your packages' tests. It runs the root's.

The root script solved ordering, but typing -w @acme/core all day gets old. Is there a better way to aim at one package?

How do you filter to just one workspace?

NPM doesn't have a separate "filter" command. The -w (or --workspace) flag is the filter.

Quick version:

npm run build -w @acme/core
npm run build -w packages/core
npm run build -w core

All three target the same package. The docs say valid values are a workspace name, a path to a workspace directory, or a path to a parent directory, which selects every workspace inside it. The short folder name works in practice too, but I'd use the package name in scripts because it survives folder renames.

Pass -w more than once to pick several:

npm run build -w @acme/core -w @acme/app

Real-world version. Adding dependencies is where -w earns its keep:

npm install dayjs -w @acme/core
npm uninstall dayjs -w @acme/core

The dependency lands in core's package.json, and the root lockfile updates. You never hand-edit the wrong file again.

Want to include the root project in a workspace run? Use --include-workspace-root:

npm run lint -ws --include-workspace-root --if-present

And the escape hatch: --workspaces=false tells npm to ignore workspaces for a command, which is handy when a config file sets them on by default.

For smarter filtering, use npm query. It takes CSS-like selectors:

npm query ".workspace"
npm query ".workspace[name^=@acme]"

Both print a JSON array of matching packages. It's a good way to feed names into a script, though I'd keep it for CI tooling and not daily use.

Under the hood. -w doesn't change which tree gets built. The whole repo still has one dependency tree. The flag only narrows which packages the command runs against. That's also why installing with -w can still touch the shared lockfile and hoisted node_modules.

Here's a quick mid-article check: do you target workspaces by name or by folder in your own scripts? Tell me which and why in the comments. I'm curious whether folder paths are still winning out there.

Filtering gets one package. What about running several at the same time?

Can NPM workspaces run scripts in parallel?

Not by themselves. --workspaces goes one at a time. Anyone claiming otherwise is describing a different tool.

Quick version. For long-running tasks like watch mode, add concurrently at the root:

npm install -D concurrently

Give each package a watch script:

{
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch --preserveWatchOutput"
  }
}
{
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch --preserveWatchOutput",
    "start": "node dist/index.js"
  }
}

Then wire both together from the root:

{
  "scripts": {
    "build": "npm run build -w @acme/core && npm run build -w @acme/app",
    "dev": "concurrently -n core,app \"npm run dev -w @acme/core\" \"npm run dev -w @acme/app\""
  }
}

Run npm run dev and you'll see interleaved, labeled output like:

[core] Starting compilation in watch mode...
[app] Starting compilation in watch mode...
[core] Found 0 errors. Watching for file changes.
[app] Found 0 errors. Watching for file changes.

Real-world version. Parallel is for independent work, like watchers and linters. Do not run builds in parallel when one package consumes another's output. That's the build-order bug again, but now it's flaky instead of consistent, which is worse. Flaky bugs eat evenings.

My rule: sequential && for builds, parallel for watchers.

Under the hood. concurrently just spawns child processes and prefixes their output. Each npm run ... -w call is its own npm process doing its own tree lookup. That's fine for a handful of packages. If you find yourself orchestrating dozens with caching and a task graph, that's the point to look at a dedicated build tool, such as Turborepo or Nx, and keep npm workspaces underneath for installs.

Workspaces handle installs and linking. They aren't a task runner, and that's okay.

Next up is the trap I teased earlier, the sibling of the stale dist folder.

What's the hoisting trap that hides missing dependencies?

Because npm hoists shared dependencies to the root node_modules, a package can import something it never declared and still work.

Quick version: the wrong version that still runs. Say core uses dayjs and declares it. App imports it too, but forgot to add it to its own package.json:

import dayjs from "dayjs";
import { formatPrice } from "@acme/core";
console.log(`${dayjs("2026-01-15").format("YYYY-MM-DD")}: ${formatPrice(1999)}`);
npm install dayjs -w @acme/core
npm run build
npm run start -w @acme/app

Expected output:

2026-01-15: $19.99

It works, because dayjs sits in the root node_modules where app's Node resolution finds it. The bug is invisible until someone publishes @acme/app on its own, or moves it to another repo, and it explodes with "module not found."

Real-world version. The fix is boring and correct: declare what you import.

npm install dayjs -w @acme/app

Now both packages list dayjs themselves. npm still stores one copy at the root if the versions agree, so you keep the disk savings and the honesty.

My opinion: this is the number one thing most developers get wrong with workspaces. They treat the root node_modules like a shared bucket. It's a cache of the tree, not a permission slip.

Under the hood. Hoisting is a dedupe optimization in the tree builder, and Node's resolution walks up parent folders looking for node_modules. The two together create "phantom dependencies." Stricter package managers fight this by design. With npm you have to enforce the discipline yourself, for example through a lint rule or a quick review habit.

Last stretch. Workspaces have more commands that keep your packages consistent with each other.

What other workspace features keep packages in sync?

Most npm commands accept -w or -ws. Four are worth knowing.

  • Scaffold a new package. npm init -w creates the folder if it doesn't exist and adds it to the root workspaces setup:
npm init -w ./packages/utils -y
  • Edit package.json fields everywhere. This is my favorite consistency tool:
npm pkg set engines.node=">=20" --workspaces
npm pkg get version --workspaces

The first sets the same Node engine range in every package. The second prints each package's version, keyed by name.

  • Version and publish selectively:
npm version patch -w @acme/core
npm publish -w @acme/core
  • Run any binary in one package:
npm exec -w @acme/app -- tsc --noEmit

Here's the full running example one more time, the root file you should end up with:

{
  "name": "acme",
  "version": "1.0.0",
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "build": "npm run build -w @acme/c
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.