← Back to Node.js, page 7

nodejs-0129 · Easy fresher

What are npm workspaces, and how do they help in a monorepo with several Node.js packages?

A monorepo keeps several packages in one repository. With npm workspaces, the root package.json lists package folders, one npm install installs all dependencies into a shared node_modules, and packages that depend on each other are symlinked instead of downloaded. You can run scripts in one or all workspaces with -w and --workspaces. pnpm, Yarn and tools like Turborepo or Nx add faster installs and task caching.

Full answer

Why a monorepo

  • Shared code (a core library) and several apps live together with one version history and one pull request for a change across packages.
  • One install, one lockfile, one set of tooling.

npm workspaces

  • Root package.json: { "private": true, "workspaces": ["packages/*"] }. The root is private so it is never published by mistake.
  • Each workspace has its own package.json with a name. Packages refer to each other by name and version range. npm sees that the package is local and creates a symlink in node_modules (node_modules/@school/core points to packages/core). There is no publish step to test a change.
  • Hoisting: shared third-party dependencies are placed in the root node_modules to save space. If versions conflict, npm nests the copy in the workspace.
  • Commands: npm install -w packages/web adds to one workspace. npm run build -w @school/web runs one script. npm run test --workspaces --if-present runs it everywhere that defines it. npm ls shows the tree.
  • Run scripts in dependency order yourself, or use a task runner. npm does not sort workspaces by dependency.

Common problems

  • Phantom dependencies: because of hoisting, code can import a package that it did not declare, and it breaks when published. Declare every import. pnpm blocks this by design.
  • Versioning and publishing: tools such as changesets or Lerna manage versions and changelogs.
  • Slow CI: use affected-only builds and caching with Turborepo or Nx.
  • TypeScript: use project references or build outputs so packages see each other's types.

Alternatives: pnpm workspaces (strict, fast, content-addressable store), Yarn workspaces. The concept is the same.

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mono-'));
const write = (file, text) => { fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); fs.writeFileSync(path.join(dir, file), text); };

write('package.json', JSON.stringify({ name: 'school-root', private: true, workspaces: ['packages/*'] }));
write('packages/core/package.json', JSON.stringify({ name: '@school/core', version: '1.0.0', main: 'index.js' }));
write('packages/core/index.js', "exports.greet = (name) => 'Hello ' + name + ' from core';");
write('packages/web/package.json', JSON.stringify({
  name: '@school/web', version: '1.0.0',
  dependencies: { '@school/core': '^1.0.0' },
  scripts: { start: "node -e \"console.log(require('@school/core').greet('Asha'))\"", test: "node -e \"console.log('web tests ran')\"" },
}));
write('packages/core/package.json', JSON.stringify({ name: '@school/core', version: '1.0.0', main: 'index.js', scripts: { test: "node -e \"console.log('core tests ran')\"" } }));

const npm = (...args) => spawnSync('npm', args, { cwd: dir, encoding: 'utf8' });
const install = npm('install', '--offline', '--no-audit', '--no-fund');
console.log('npm install exit code:', install.status);

const link = path.join(dir, 'node_modules', '@school', 'core');
console.log('node_modules/@school/core is a symlink:', fs.lstatSync(link).isSymbolicLink());
console.log('it points to:', path.relative(path.join(dir, 'node_modules', '@school'), fs.realpathSync(link)));
console.log('run one workspace:', npm('run', 'start', '-w', '@school/web', '--silent').stdout.trim());
const all = npm('run', 'test', '--workspaces', '--if-present', '--silent').stdout.trim().split('\n').sort();
console.log('run in all workspaces:', all.join(' | '));

fs.rmSync(dir, { recursive: true });

A temporary monorepo with two packages is installed without network access. The script shows the symlink and runs scripts in one and in all workspaces. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): npm install exit code: 0 node_modules/@school/core is a symlink: true it points to: ../../packages/core run one workspace: Hello Asha from core run in all workspaces: core tests ran | web tests ran

Key points

  • Workspaces are listed in the root package.json.
  • Local packages are symlinked, not downloaded.
  • Shared dependencies are hoisted to the root.
  • -w and --workspaces run scripts in selected packages.
  • Declare all imports to avoid phantom dependencies.

Common mistakes

  • Forgetting private: true in the root package.json.
  • Importing a package that is only available because of hoisting.
  • Running npm install inside a workspace folder and creating a second lockfile.
  • Building packages in the wrong order.
  • Publishing all packages with the same version without a release tool.

Follow-ups

  • How do pnpm workspaces differ from npm workspaces?
  • What does Turborepo or Nx add on top of workspaces?
  • How do you share TypeScript types between packages?

Tips

  • Give the three facts: workspaces list, symlink, hoisting.
  • Mention phantom dependencies as a real risk.
  • Name pnpm and a task runner as the next step.