[FEE-805] Monorepos & Workspaces
INFO
Teams that split every package into its own git repository hit a wall once a change needs to cross package boundaries: a single logical fix turns into several PRs, several publishes, and a coordination window. This article covers why the monorepo model removes that overhead, and how Turborepo and Nx add a cached, parallel task graph on top of raw workspace tooling from pnpm, Yarn, npm, and Bun. It walks through the concrete configuration, pnpm-workspace.yaml, turbo.json, and the workspace:* protocol, uses Turborepo as the primary worked example, and closes with where a monorepo is the wrong answer and Module Federation is the alternative.
Context
In the early days of frontend engineering, each project lived in its own git repository. That model, known as the polyrepo, gives teams full autonomy: independent deployment cycles, separate CI pipelines, and package manager lockfiles that never conflict. It works well when packages evolve independently and changes rarely cross boundaries.
At scale, the polyrepo model breaks down. A UI design system shared by five applications is a separate npm package. To ship a fix that touches the design system and two consuming apps, a team must open three PRs across three repositories, coordinate three reviews, publish a new design system version to npm, update the dependency in each consuming app, and wait for a propagation window. The actual code change, often five lines or fewer, is buried in a multi-day, multi-team coordination problem. Git submodules are the classic escape hatch, but they are famously fragile: submodule state is not automatically synchronized, nested submodules create deep trees of manual updates, and CI configuration duplicates across every consumer.
The monorepo model puts all related packages (applications, libraries, shared configs) into a single git repository. A change that spans three packages is a single commit, a single PR, a single CI run. Internal packages reference each other directly by symlink rather than through a registry publish cycle. Tooling, CI configuration, and lint rules are shared at the root.
This is not a new idea. Google, Meta, and Microsoft have operated monorepos at millions-of-files scale for over a decade. In the JavaScript ecosystem, projects like Babel, Jest, React, and Vue adopted monorepos early. The challenge for most teams was tooling: npm install does not understand multi-package workspaces, and running npm run build in every package manually does not scale. Lerna (2015) and Rush (2017) were the first widely used JavaScript monorepo task orchestrators, handling per-package script execution and multi-package publishing; package managers added native workspace support later (npm 7 in 2020, pnpm and Yarn earlier). Turborepo and Nx are the current mainstream orchestrators, adding the content-hashed cache and dependency-aware task graph that classic Lerna lacked (Rush already had hash-based incremental and parallel builds, but stayed more niche in the JavaScript ecosystem); Lerna itself now delegates task execution to Nx rather than competing with it.
This article uses Turborepo as the primary worked example, because its minimal configuration surface keeps the task graph and cache directly visible, and treats Nx, pnpm/Yarn/npm workspaces, and Bun workspaces comparatively throughout.
Visual
Turborepo Task DAG
The diagram below shows a small monorepo with three tasks across two apps and one shared library, modeled as a directed acyclic graph (DAG). Arrows point from dependency to dependent: a task waits for everything its arrow points from.
With dependsOn: ["^build"] configured, turbo run build test will:
- Build
packages/uifirst (no upstream dependencies). - Build
apps/webandapps/docsin parallel oncepackages/ui:buildcompletes. - Run
apps/web:testafterapps/web:buildcompletes.
If packages/ui's source files have not changed since the last run, step 1 is a cache hit. Turborepo restores dist/ from cache and skips re-executing the build script.
Example
1. pnpm-workspace.yaml
Place at the repository root. Declares which directories contain workspace packages.
packages:
- 'apps/*' # Next.js apps, Remix apps, etc.
- 'packages/*' # Shared libraries and configs
# Explicitly exclude directories that are not real packages.
- '!**/test/**'
- '!**/fixtures/**'2. turbo.json: task configuration
Turborepo reads this file at the repository root. Each key in tasks is a task name that maps to package.json scripts entries.
{
"$schema": "https://turborepo.dev/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**", "!.next/cache/**"]
},
"test": {
"dependsOn": ["build"],
"outputs": []
},
"lint": {
"outputs": []
},
"dev": {
"cache": false,
"persistent": true
}
}
}Key properties:
dependsOn: ["^build"]: the^prefix means "runbuildin all upstream dependencies first." An app that depends on a library will build the library before building itself.dependsOn: ["build"](no^): the same package'sbuildmust complete beforeteststarts. Used for same-package ordering.outputs: the file globs Turborepo caches. On a cache hit, these files are restored from cache instead of re-running the script. Empty array means no file outputs are cached (logs are still cached).cache: false: disables caching entirely. Used fordevservers and other long-running tasks that should never be cached.persistent: true: marks tasks that run indefinitely (dev servers). Turborepo runs these last and keeps them alive.
3. Root package.json with workspace scripts and turbo
{
"name": "my-monorepo",
"private": true,
"scripts": {
"build": "turbo run build",
"test": "turbo run test",
"lint": "turbo run lint",
"dev": "turbo run dev",
"build:web": "turbo run build --filter=./apps/web"
},
"devDependencies": {
"turbo": "^2.0.0"
},
"packageManager": "pnpm@9.15.0"
}Running a filtered build (only apps/web and its dependencies):
turbo run build --filter=./apps/webThe --filter flag accepts package names, glob paths, or git-based expressions:
# All packages changed since branching from main
turbo run build --filter=...[origin/main]
# A specific package and all packages that depend on it
turbo run build --filter=...packages/ui...4. Internal package: packages/ui/package.json
{
"name": "@myrepo/ui",
"version": "0.0.1",
"private": true,
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"build": "tsc --project tsconfig.build.json",
"dev": "tsc --watch"
},
"devDependencies": {
"typescript": "^5.4.0"
}
}A consuming app references it with the workspace:* protocol:
{
"name": "@myrepo/web",
"dependencies": {
"@myrepo/ui": "workspace:*"
}
}workspace:* tells pnpm to resolve @myrepo/ui to the local workspace package and create a symlink in node_modules. The * is replaced with the actual version number when the package is published (e.g., pnpm publish). During development, importing from @myrepo/ui resolves through the symlink directly to the dist/ directory (or source, if configured with TypeScript paths).
Yarn and Bun support the same workspace:* protocol. npm workspaces use "*" as the version value instead, but the symlink behavior is equivalent. Turborepo works across pnpm, npm, Yarn, and Bun workspaces.
5. pnpm recursive run without Turborepo
For small monorepos, a task runner may be overkill. pnpm's built-in recursive commands are sufficient:
# Build all packages in dependency order (pnpm infers order from workspace deps)
pnpm -r run build
# Run a script only in packages that have it defined
pnpm -r run test --if-present
# Run in a specific package
pnpm run build --filter @myrepo/uiUpgrade to Turborepo when CI times start to hurt. The turbo.json can be layered onto an existing pnpm workspace without restructuring anything.
6. Nx: project graph and affected runs
Nx does not require a nx.json tasks declaration for every script; it infers the project graph from package.json dependencies and source imports.
# Only run build and test for packages changed since main
nx affected -t build test
# Visualize the project graph in the browser
nx graph
# Generate a new library package
nx generate @nx/js:library packages/utils
# Run a single package
nx run @myrepo/ui:buildnx affected compares the current branch against the base branch (default: main), identifies which files changed, traces which packages own those files via the project graph, and runs tasks only for affected packages and their dependents. On a fifty-package monorepo where a single utility changed, nx affected might run tasks for three packages instead of fifty, a significant CI time reduction without needing to configure filters manually.
Best Practices
SHOULD declare outputs explicitly in every turbo.json task, including all directories the task writes to. If outputs is omitted, Turborepo marks a task as cached but does not restore any files on a cache hit. A downstream task that expects dist/ to exist will fail. Every directory the build script writes ("dist/**", ".next/**", "build/**") must appear in outputs so Turborepo can restore them on a cache hit.
MUST mark the root package.json and all internal-only packages with "private": true. The monorepo root is a workspace manifest, not a publishable package. Without "private": true, running pnpm publish at the root accidentally publishes the manifest. All workspace roots and packages intended only for internal consumption MUST be marked private to prevent accidental registry publication.
SHOULD manage workspace dependencies from the repository root, not from inside individual package directories. Running npm install or pnpm install inside a package subdirectory creates a separate node_modules and lockfile in that directory, which breaks workspace symlinks and creates a conflicting, isolated dependency resolution. Always use pnpm add <package> --filter <workspace> from the root to install dependencies into a specific workspace.
SHOULD start with pnpm -r run build and add Turborepo only when CI time becomes a concrete problem. For monorepos with five or fewer packages, recursive pnpm commands are sufficient. Turborepo's task DAG, caching, and parallel execution become worthwhile when sequential builds or rebuilding unchanged packages visibly slows CI. Adopting Turborepo incrementally by adding turbo.json to an existing workspace requires no restructuring.
SHOULD mark tasks that have non-deterministic outputs or make network calls with "cache": false in turbo.json. Turborepo's cache is content-hash-based: the same inputs always produce the same cache hit. If a task fetches live data, writes timestamps, or produces random output, caching will restore stale results. Dev server tasks (dev) should also be marked "cache": false and "persistent": true so Turborepo runs them last and keeps them alive.
Design Thinking
Why monorepos win for large teams: the cross-cutting change problem. In a polyrepo, sharing code requires either publishing to npm (slow feedback loop: publish, wait for propagation, update consumer's package.json, install, test) or using git submodules (fragile, manual, error-prone). A refactor that touches a shared utility and three consumers requires coordinated changes across four repositories, four PRs, and four CI pipelines, with no way to make the change atomic. If the refactor is staged (ship the library first, then update consumers), the intermediate state where some consumers use the new API and some use the old API must be managed explicitly. In a monorepo, the same refactor is one commit, one PR, one CI run.
Why pnpm -r run build is not enough at scale. pnpm's recursive run (pnpm -r run build) iterates over all workspace packages and runs their build script. For a small monorepo with five packages, this is entirely sufficient. For a monorepo with fifty packages, it has two problems. First, it is sequential by default: packages build one at a time, even when they have no dependency on each other. A CI run that could finish in four minutes of parallel work takes twenty minutes. Second, there is no caching: every CI run rebuilds every package from scratch, even packages whose source files have not changed since the last run. Turborepo and Nx solve both problems by modeling tasks as a dependency graph (DAG), running independent tasks in parallel, and hashing task inputs to skip tasks whose outputs are already cached.
Why Turborepo and Nx diverge in philosophy. Turborepo is minimal by design. It adds a task DAG and a caching layer to your existing package manager and existing package.json scripts, in one configuration file (turbo.json). It leaves project structure, scaffolding, and boundary rules to you. This makes it easy to adopt incrementally: you can add Turborepo to an existing pnpm workspace in an afternoon.
Nx is opinionated and comprehensive. It builds a detailed project graph from source analysis, tracks every file dependency between packages, provides code generators (nx generate), enforces module boundary rules via an ESLint plugin, and offers distributed task execution (Nx Cloud) with fine-grained replay of individual task results. The additional power requires more configuration and a steeper learning curve. Nx is the better choice when a large organization needs governance: enforced boundaries between team-owned packages, centrally managed generators for consistent scaffolding, and granular visibility into which tasks ran, on which CI agents, and why.
The polyrepo vs monorepo tradeoff. Monorepos require upfront tooling investment: workspace configuration, a task runner, a coherent dependency strategy. Very large repositories (millions of files, hundreds of packages) can stress git operations: git status, git log, and IDE indexing become slow. Companies operating at that scale use custom tooling built for the problem: Meta uses a Mercurial derivative (Sapling) with the EdenFS virtual filesystem, and Google uses Piper with a FUSE-based virtual filesystem, tools that most teams will never need. For most teams, up to a few hundred packages, a pnpm workspace with Turborepo or Nx handles the scale comfortably. The stronger argument against monorepos is team autonomy: every team shares the same CI pipeline, the same root tooling configuration, and the same release gate. A flaky test in one package blocks the whole CI run. Establishing clear ownership (via CODEOWNERS) and task filtering (turbo run build --filter=./apps/web) mitigates this, but the coordination overhead is real.
Internal packages: source vs compiled. Internal packages (a shared design system, a utility library, a common types package) can be consumed in two ways. The simpler approach: configure TypeScript paths in the root tsconfig.json to map the package name to its source directory. Consuming packages import directly from source; no build step is needed for the internal package. This works well for TypeScript-only packages with no separate compile step. The more explicit approach: the internal package has its own build script that produces a dist/ directory, and consuming packages reference dist/. This mirrors how the package would be used if published externally, and Turborepo can cache the build so consuming apps do not rebuild the library unless its source changes.
Common Mistakes
Using workspace:* in a public package that will be published.workspace:* is a development-time protocol. pnpm and Yarn replace it with the actual version number on pnpm publish. If you accidentally commit a package.json with workspace:* in a public (non-private) package without publishing through the workspace toolchain, the published tarball will contain a literal workspace:*, which is not resolvable from the npm registry. Always publish workspace packages via pnpm publish or Changesets, never by manually packing.
Treating Nx as a drop-in replacement for Turborepo. Turborepo is a task runner with caching. Nx is a full monorepo platform with its own project graph, generators, and lint rules. Migrating from Turborepo to Nx is not a configuration rename; it requires learning Nx's project detection, executor system, and boundary enforcement. Evaluate which tool fits your team's needs before committing. The simpler team should default to Turborepo; the team that needs enforced ownership and enterprise-scale governance should evaluate Nx.
Ignoring Module Federation as an alternative. Module Federation (Webpack 5 / Rspack) is an alternative to monorepos for code sharing: independently deployed applications load each other's modules at runtime via remote URLs rather than importing them at build time. This avoids the shared build entirely: each app is built and deployed independently. The tradeoff is runtime coupling: if the remote app is down or ships a breaking API change, the consuming app breaks at runtime rather than at build time. Module Federation works well when teams need fully independent deployment cycles and are willing to manage runtime version compatibility. It is the wrong tool when the goal is atomic cross-cutting changes; that problem requires a monorepo.
Related Topics
- FEE-800: Build Tooling & Module Systems Overview. The broader pipeline that monorepo tooling is part of.
- FEE-804: Package Management (npm, pnpm & Yarn). The workspace protocol, lockfiles, and
--frozen-lockfilethat underpin workspace setup. - FEE-807: Build Optimization. Turborepo remote caching (Vercel, S3, GitHub Actions cache) and cache key strategies in CI.
References
- Turborepo: Configuring tasks
- Turborepo: Caching
- Turborepo: Remote Caching
- Turborepo: turbo.json reference
- Nx: Mental Model
- Nx: Run Only Tasks Affected by a PR
- Nx: Distribute Task Execution
- pnpm: Workspaces
- pnpm: pnpm-workspace.yaml
- Nx: What is a Monorepo?
- Rachel Potvin and Josh Levenberg, "Why Google Stores Billions of Lines of Code in a Single Repository," Communications of the ACM, vol. 59 (2016). https://cacm.acm.org/research/why-google-stores-billions-of-lines-of-code-in-a-single-repository/
- Steve Kinney, "Turborepo versus Nx, Bazel, Lerna, and Friends," Enterprise UI. https://stevekinney.com/courses/enterprise-ui/turborepo-versus-nx
- "Monorepo in 2026: Turborepo vs Nx vs Bazel for Modern Development Teams," daily.dev (2026). https://daily.dev/blog/monorepo-turborepo-vs-nx-vs-bazel-modern-development-teams/