DEV Community

Cover image for NPM Workspaces: Why Does My Monorepo Build Work Locally but Break in CI?
Rajat
Rajat

Posted on

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 nobody warns you about

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
// acme/package.json
{
  "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"
  }
}
Enter fullscreen mode Exit fullscreen mode

(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.

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

Now the consumer:

// acme/packages/app/package.json
{
  "name": "@acme/app",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  },
  "dependencies": {
    "@acme/core": "*"
  }
}
Enter fullscreen mode Exit fullscreen mode
// acme/packages/app/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode
// acme/packages/app/src/index.ts
import { formatPrice } from "@acme/core";

console.log(formatPrice(1999));
Enter fullscreen mode Exit fullscreen mode

Run one install from the root:

cd acme
npm install
ls -l node_modules/@acme
Enter fullscreen mode Exit fullscreen mode

Expected output (trimmed):

core -> ../../packages/core
app -> ../../packages/app
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Expected output (trimmed):

> @acme/app@1.0.0 build
> tsc

> @acme/core@1.0.0 build
> tsc
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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:

// acme/package.json (scripts section)
{
  "scripts": {
    "build": "npm run build -w @acme/core && npm run build -w @acme/app"
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Real-world version

Adding dependencies is where -w earns its keep:

npm install dayjs -w @acme/core
npm uninstall dayjs -w @acme/core
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Give each package a watch script:

// acme/packages/core/package.json (scripts section)
{
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch --preserveWatchOutput"
  }
}
Enter fullscreen mode Exit fullscreen mode
// acme/packages/app/package.json (scripts section)
{
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch --preserveWatchOutput",
    "start": "node dist/index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then wire both together from the root:

// acme/package.json (scripts section)
{
  "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\""
  }
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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:

// acme/packages/app/src/index.ts
import dayjs from "dayjs";
import { formatPrice } from "@acme/core";

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

Expected output:

2026-01-15: $19.99
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Edit package.json fields everywhere. This is my favorite consistency tool:

npm pkg set engines.node=">=20" --workspaces
npm pkg get version --workspaces
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Run any binary in one package:

npm exec -w @acme/app -- tsc --noEmit
Enter fullscreen mode Exit fullscreen mode

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

// acme/package.json
{
  "name": "acme",
  "version": "1.0.0",
  "private": true,
  "workspaces": ["packages/*"],
  "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\"",
    "typecheck": "npm run build --workspaces --if-present -- --noEmit"
  },
  "devDependencies": {
    "@types/node": "^22.0.0",
    "concurrently": "^9.0.0",
    "typescript": "^5.6.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

I kept typecheck out of the earlier sections on purpose. Try it, and think about why --noEmit against app would fail on a clean checkout (hint: same cause as before, no core types without a core build). That's your homework.

Bonus tips, one per level

  • Beginner: run npm ls --workspaces from the root to see every package and its dependencies at a glance.
  • Real-world: commit the root package-lock.json and use npm ci in CI. One lockfile means one source of truth.
  • Under the hood: if a package behaves differently locally than in CI, delete node_modules and every dist, run npm ci, and rebuild. That recreates the clean-checkout world on your own machine.

Back to that red pipeline

Remember 6:40 pm and the missing @acme/core? Your laptop had a stale dist folder quietly doing the job that build ordering should have done. CI had no such luxury. Workspaces gave you linking, one lockfile, and one install. They did not give you a dependency-aware build order, and they never promised to.

Here's the recap:

  1. Workspaces link local packages through one root install and one lockfile.
  2. -workspaces runs scripts one by one, in npm's order, not your dependency order.
  3. w filters by name, path, or parent folder, and works on install, version, publish, and exec.
  4. Parallel work needs a helper like concurrently, and it belongs to watchers, not builds.
  5. Hoisting hides undeclared imports. Declare what you import.
  6. npm pkg set --workspaces keeps shared metadata identical everywhere.

Further reading from folks who've covered this ground: Faiz Ahmed on npm workspaces, a gentle intro from Wasp, Safeguard's dependency walkthrough, the Publishing Project's take, and Paul Serban's guide. If a teammate keeps fighting this exact monorepo build bug, send them this article.

What did you think?

Did this approach match how you are solving it, or do you have a different take? Drop a comment. I genuinely read every single one.

Found this helpful?

If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.

Want more tips like this?

I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.

Let us connect. Find me on LinkedIn or GitHub and let us keep the conversation going.


Follow Me for More Angular & Frontend Goodness:

I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.

  • 💼 LinkedIn — Let’s connect professionally
  • 🎥 Threads — Short-form frontend insights
  • 🐦 X (Twitter) — Developer banter + code snippets
  • 👥 BlueSky — Stay up to date on frontend trends
  • 🌟 GitHub Projects — Explore code in action
  • 🌐 Website — Everything in one place
  • 📚 Medium Blog — Long-form content and deep-dives
  • 💬 Dev Blog — Free Long-form content and deep-dives
  • ✉️ Substack — Weekly frontend stories & curated resources
  • 🧩 Portfolio — Projects, talks, and recognitions
  • ✍️ Hashnode — Developer blog posts & tech discussions
  • ✍️ Reddit — Developer blog posts & tech discussions

Top comments (0)