Sub topic 16
When to Move to a Monorepo with Packages
This chapter assumes you have read the earlier chapters on feature modules, public APIs, path aliases, and ESLint boundary rules. You should know npm, a bundler such as Vite, and basic TypeScript configuration.
A feature-based layout inside one src/ folder solves most structure problems. Some teams outgrow it. This chapter explains what a monorepo with workspace packages adds, what it costs, and how to tell whether you need it.
What a monorepo with packages is
A monorepo is one Git repository that holds several separately named units of code. In the JavaScript world, those units are workspace packages. Each package has its own package.json, its own public entry point, and its own declared dependencies. A package manager such as npm, pnpm, or Yarn links the packages together so they can import each other by name.
Compare this with the folder boundaries you built earlier. A feature folder is a boundary enforced by convention and by a lint rule. A package is a boundary enforced by the package manager and the module resolver. Code in one package cannot import a file from another package unless that package exposes it, and it cannot import a dependency it has not declared.
A typical layout looks like this:
repo/
package.json
pnpm-workspace.yaml
apps/
web/
package.json
src/
admin/
package.json
src/
packages/
ui/
package.json
src/
index.ts
api-client/
package.json
src/
index.ts
config-eslint/
package.jsonApplications live in apps/. Libraries shared between them live in packages/. Apps depend on packages. Packages never depend on apps.
Signs that you need it
A monorepo is a response to specific pressure. Look for these signals before you change anything.
- A second application appears. You need an admin tool, a marketing site, or a mobile web shell that reuses your design system and API types. Copying files between repositories drifts quickly.
- A shared layer has its own release rhythm. The design system changes on a different schedule from the product, and several teams consume it.
- Build or test times hurt. Every change rebuilds and retests everything, and you want to rebuild only what a change affects.
- Teams need hard ownership lines. Lint rules are being bypassed with disable comments, and you want boundaries that cannot be bypassed casually.
- You want one place for tooling. ESLint, TypeScript, and test configuration are duplicated across repositories and have diverged.
These signals are weaker or absent in many projects:
- The codebase is large but has one application and one team.
- You want "cleaner" structure but have no consumer for the extracted code.
- Folder boundaries are not yet enforced. Fix that first, using the lint rule from the previous chapters.
A single application with well-enforced feature boundaries is usually the better choice. Packages add setup and maintenance work that only pays off when something consumes them.
What to extract first
The concept graph for this tutorial points to two natural starting points: the shared UI layer and the boundary rules. Both are already isolated from feature code, which makes them cheap to move.
- Shared UI (
src/shared/ui) becomespackages/ui. It has no dependency on features, so nothing needs untangling. - API types and client code that more than one app needs become
packages/api-client. - Tooling configuration (ESLint, TypeScript base config) becomes a config package.
Feature modules usually stay inside the app that owns them. Extract a feature into a package only when a second app genuinely uses it.
Setting up workspaces
With pnpm, the workspace file lists where packages live.
# pnpm-workspace.yaml
packages:
- "apps/*"
- "packages/*"With npm or Yarn, you declare the same thing in the root package.json instead.
{
"name": "repo",
"private": true,
"workspaces": ["apps/*", "packages/*"]
}Each package declares a name and an entry point. The exports field is the package-level version of the feature index.ts file. Anything not listed there cannot be imported from outside.
{
"name": "@acme/ui",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
".": "./src/index.ts"
},
"peerDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
}An app then declares the dependency using the workspace protocol:
{
"name": "@acme/web",
"private": true,
"dependencies": {
"@acme/ui": "workspace:*",
"@acme/api-client": "workspace:*"
}
}Run the install command once at the root. The package manager links @acme/ui into the app's node_modules, so import { Button } from "@acme/ui" resolves like any installed library. Note that npm uses "*" rather than workspace:*, which only pnpm and Yarn support.
Pointing exports at source
The exports example above points at TypeScript source, not built output. This is the "just-in-time" package style. The app's bundler compiles the package as if it were app code. It avoids a separate build step and gives fast refresh across packages. The trade-off is that the consuming bundler must be configured to transpile files under node_modules links, and the package cannot be published to npm as is.
The alternative is to build each package to dist/ and point exports at the output. This costs build orchestration, but the package works with any consumer and can be published. Choose source exports while all consumers live in the repo. Switch to built output when you publish.
Cross-package concerns
Splitting into packages creates problems that single-app structure never had.
Peer dependencies and duplicate React
A UI package that bundles its own copy of React breaks hooks, because two React instances do not share internal state. The usual error is "Invalid hook call". Declare react as a peer dependency in the package, as shown above, and let the app supply it. Keep one React version across the whole repository.
TypeScript project setup
Each package should extend a shared base config rather than copy settings. A common arrangement is a base file at the root of the config package, extended by each app and package.
{
"extends": "@acme/config-ts/base.json",
"compilerOptions": {
"jsx": "react-jsx",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}The @/* alias is scoped to the package it lives in. Inside apps/web, @/ means apps/web/src. Inside packages/ui, it means packages/ui/src. Never use the alias to reach into another package. Cross-package imports use the package name.
Boundary rules change shape
Your earlier no-restricted-imports rule blocked @/features/*/*. In a monorepo you add a second rule: block deep imports into packages, such as @acme/ui/src/Button. The exports field already prevents this at resolution time for most tools, and the lint rule gives a clearer message in the editor.
Dependency direction
The one rule to hold firmly: apps depend on packages, and packages do not depend on apps. A package that imports from an app creates a cycle and defeats the purpose. If a package needs something an app owns, pass it in through props, context, or a function argument.
Build and task orchestration
Once there are several packages, running build or test in every one on each change wastes time. Task runners such as Turborepo and Nx read the dependency graph between packages. They run tasks in dependency order, run independent tasks in parallel, and cache results so that unchanged packages are skipped.
You do not need a task runner on day one. With two or three small source-exported packages, plain workspace scripts are enough. Add a runner when CI time becomes a complaint. A cache that is not configured carefully can also return stale results, so add one deliberately and check that inputs such as environment variables are declared.
Costs to weigh
| Benefit | Cost |
|---|---|
| Hard boundaries enforced by dependencies | More `package.json` and config files to keep consistent |
| Shared code reused by several apps | Changes to a package affect every consumer at once |
| Affected-only builds and tests with a task runner | Extra tooling to learn and debug |
| One version of each dependency | Upgrades touch the whole repository together |
| Atomic changes across app and library | Longer clone times and a larger CI surface |
A migration path
Apply the same incremental approach as the earlier migration chapter.
- Enforce feature boundaries with ESLint in the single app.
- Add the workspace configuration and move the existing app into
apps/webwithout changing its code. - Extract
shared/uiintopackages/uiand replace@/shared/uiimports with@acme/ui. - Extract shared API types and the base TypeScript and ESLint configs.
- Add a task runner only if build time justifies it.
Verify the build and tests after each step. Each step can ship on its own.
Exercise
Your team has one React app, one team, and a slow, tangled src/ folder where features import each other's internal files. A colleague proposes moving to a monorepo with a package per feature. What would you recommend first, and why?
Show answer
Enforce feature boundaries inside the single app first: give each feature an index.ts public API, add path aliases, and add the no-restricted-imports rule so deep imports fail. The problem is missing boundaries, not missing packages. A package per feature adds setup and maintenance cost without a second consumer. Reconsider a monorepo when a second app or an independently versioned shared library appears.
Exercise
An app imports a Button from a workspace package @acme/ui, and hooks inside the Button fail with "Invalid hook call". What is the most likely cause and the fix?
Show answer
The package probably has react as a regular dependency, so two copies of React are installed and the app and package do not share hook state. Move react and react-dom to peerDependencies in the package, keep one version across the repo, and reinstall so only one copy resolves.