Est.

Module Boundary Design in Large TypeScript Monorepos

Enforce TypeScript monorepo architecture automatically instead of relying on code review alone.

Sponsored by Graphide

The Architecture Graph Editors
· 8 min read · Updated
Cover illustration for “Module Boundary Design in Large TypeScript Monorepos”
Codebase Architecture · October 27, 2026 · 8 min read · 1,789 words

Module boundary design in large TypeScript monorepos is the work of turning package structure into enforceable architectural contracts. Public APIs, domain-aligned packages, and CI-enforced dependency rules keep that structure coherent as the codebase grows. For AI agent steering, a codebase graph must show where files live, which dependencies are allowed, and which contracts are changing. Its value comes from connecting that map to automatic enforcement.

Why module boundaries in a TypeScript monorepo are an architectural problem, not an organizational one

A team scaffolds a workspace and creates libraries, and the first few sprints feel intentional. Then a developer imports a formatting utility directly from payments, another borrows a loans component for an accounts prototype, and someone reaches into an unrelated domain’s internal service. CI passes with all of those imports in place. The folders still look orderly, but the architecture diagram and the actual import graph have begun to diverge.

This is a tooling problem. Code review cannot reliably police every dependency once a repository grows beyond a small team and a handful of libraries. In that setting, types are no longer just local annotations. Every shared interface creates obligations for consumers, while every cross-package import establishes a structural relationship that future changes must respect.

A monorepo does not have to become a monolith. Without enforceable rules, however, its failure mode is high coupling and low cohesion, with packages importing whatever happens to be available. The defining property of a well-run monorepo is therefore one coherent, rule-governed dependency graph. A boundary states what a package exposes, what it depends on, and what it must not touch.

How the package boundary becomes a public API contract

A package’s index file shows what its public surface is meant to include. For example, packages/shared/src/index.ts can export UserSchema, formatCurrency, and the User and Product types while leaving utils/format-date.ts internal. Consumers depend on those exports. Unexported implementation details remain available for refactoring without requiring consumer changes, provided consumers cannot bypass the entry point.

The package must be more than a folder. Each package should have its own tsconfig, declared dependencies, and public API, with the package.json exports field enforcing the corresponding boundary at Node resolution time. The recommended cross-package mechanism combines the workspace: protocol with explicit exports.

Path aliases alone do not establish that contract. TypeScript states that imports depending only on baseUrl and paths cannot be rewritten when outputting JavaScript, so an alias-based design may pass type checking yet fail during execution or publishing. Keeping exports limited to what consumers genuinely need also makes the index file a living record of the contract.

Why domain-aligned splits produce more durable boundaries than layer-aligned ones

On a banking platform, payments, loans, accounts, and kyc can each form a self-contained vertical. Apps use those libraries, while domain libraries depend on code within their own scope or on shared infrastructure. The resulting rules are natural to express. Payments never imports from loans, accounts never imports from payments, and shared never depends on a domain.

A layer-aligned split works against that separation when packages are organized only as components, hooks, and utils. Each feature then spans the same technical layers. Domain alignment gives a feature a more durable home. Scope tags name that home, while type tags name the library’s role in the architecture, so enforcement rules can use both.

In the banking workspace, shared can hold genuinely cross-cutting design tokens, HTTP utilities, validators, and formatters used by multiple domains. A module consumed only by payments belongs in payments. Otherwise, shared becomes a bottleneck whose changes invalidate caches and trigger rebuilds across the graph.

Some teams duplicate a small piece of domain-specific logic instead of exposing it through a shared API that gradually becomes unmanageable. The trade-off is explicit. A little repeated code can be preferable to making loans and payments depend on an abstraction that compromises their encapsulation.

TypeScript Project References as the compiler-level boundary mechanism

TypeScript Project References treat packages as independent TypeScript programs, making their build-time relationships visible to the compiler. They provide type-checking isolation and support incremental builds ordered by dependencies. This is more than a speed optimization. TypeScript’s official documentation describes split projects as a way to improve build times and enforce logical separation, with tsc --build supporting the build process.

In practice, each package has its own tsconfig.json, strict mode, declared dependencies, and references to the packages it uses. Referenced declarations give programs a build-time interface with each other, taking over the job of defining project structure from aliases. Runtime resolution remains a separate concern. Project references handle compilation, while package exports set the runtime boundary.

That separation also defines the compiler layer’s limit. A developer can still declare a dependency that the architecture should prohibit, and the compiler can type-check that dependency correctly. Project references make the declared build graph explicit, leaving architectural policy, including whether payments ought to depend on loans, to tools that evaluate which edges are allowed.

Three enforcement tools that operate at different granularities

Nx module boundary rules apply architectural policy through tags and ESLint. Each library receives tags in its project.json, such as scope:payments, scope:shared, type:lib, or type:app, and the lint configuration defines permitted relationships. Feedback arrives during development and in CI lint runs. In the banking workspace, apps can consume libraries but not other apps, domain libraries can consume their own scope and shared, and shared can have no upward dependencies. The banTransitiveDependencies option also prevents library A from importing C merely because A depends on B and B depends on C.

Tag assignment is the weak point in this model. A library with the wrong tag inherits the wrong rules, even when those rules are otherwise correct. Nx therefore provides fast policy feedback at project granularity. Its usefulness depends on the accuracy of the metadata it evaluates.

Dependency-cruiser works at file level and outside Nx environments, expressing architecture as versioned configuration that can fail CI. Its rules can prohibit service-to-service imports, adapter imports from application code, dependencies from shared packages to consumers, and cycles. It can also enforce shared usage across at least two domains. Compatibility remains an operational concern. In a documented TypeScript 7 case, the required TypeScript API was unavailable, so the tool parsed no .ts files and passed every architecture rule without checking anything, which led that setup to pin TypeScript 6.

Sheriff, distributed as @softarc/sheriff-core, validates architectural constraints during development and at build time. It has zero runtime overhead and only TypeScript as a peer dependency. It is suited to checking architecture at build time rather than giving feedback from tags in the editor. These tools cover different enforcement surfaces, so their roles are complementary.

AST-level and test-level enforcement for cases linting cannot reach

A scanner matching strings cannot reliably distinguish a dependency reached through a re-export alias or establish where a path alias resolves. The written import is not the whole relationship. Typed architectural configuration combined with the TypeScript Compiler API can build an import graph that respects aliases and barrel re-exports.

The analysis can check where dependencies resolve instead of assuming that a matching path points to the intended module. That distinction becomes important when an architectural invariant depends on the graph behind an import. It extends enforcement beyond the granularity that tags and simple file-level scans provide.

Architectural tests provide another way to make those invariants executable. Archunit expresses rules as regular test assertions, including that src/http must not depend on src/infrastructure/repositories, or that the graph must contain no circular dependencies. The assertions read as specifications within the test suite. They fail through the same CI signal as other broken tests, without requiring a separate integration merely to report an architectural failure.

How boundary drift happens silently and what it costs when agents write the code

Boundary drift usually begins with a shortcut that leaves CI green. A developer imports one internal module under deadline, and the architecture diagram remains unchanged. Six months later, payments knows about accounts and an accounts feature imports from loans. Test isolation breaks, and refactoring becomes unsafe because the real consumers are no longer constrained by the intended contracts.

The checking cost grows with that entanglement. Without caching and awareness of the graph, each new package gives CI more work, and a change to a shared TypeScript type can break four downstream apps. When CI omits consumers, the compiler may catch the incompatibility eventually but not before the pull request merges.

AI coding agents accelerate the same failure mechanism because they have no inherent model of which imports a workspace permits. The fastest route to satisfying a prompt may be a cross-domain shortcut, and a single prompt can produce changes across many files. Defined boundaries leave an agent with less of the codebase to understand. They do not let an agent enforce rules it cannot access, so enforcement must remain external, structural, and automatic.

A diff shows a changed shared type but does not, by itself, expose every downstream package that relies on it. The graph supplies the missing structural context. Developers need to ask which packages gained dependencies, which boundaries moved, and which public contracts changed, as well as how many lines the agent edited.

Making boundary enforcement a first-class CI gate, not a post-hoc review step

When a change breaks a boundary rule, CI must fail and block the merge. A design document or dismissible lint warning cannot provide that guarantee. The practical response is to commit dependency-cruiser rules, or equivalent architectural configuration, with the code and run them in the pipeline. Architectural assertions should also make the test suite fail when cross-domain imports or cycles appear.

Running tsc --build only against the changed package leaves it untested with its consumers, so a shared type change must be checked against all consumers before merge. Turborepo uses task graphs, caching, and parallel execution to make full type checking and boundary validation affordable enough to run as routine gates.

A pnpm workspace manages dependencies, TypeScript Project References define type boundaries, Turborepo handles task orchestration and caching, and package.json exports enforce runtime entry points. Architectural rules then constrain the relationships those mechanisms permit. Build correctness and structural conformance are separate checks, and both belong before merge.

Putting architectural checks in CI

Choose an architecture-test or dependency-rule tool that supports your language and the constraints you can explicitly encode. Commit its rules with the code, run the documented command in CI, and make the resulting check required where those rules should prevent a merge. Test the gate with an intentionally forbidden dependency before relying on it. Such checks enforce the rules you specify; they do not establish that every aspect of the architecture or runtime behavior is correct.

Updated November 5, 2026: obsolete CLI examples removed. Use the selected tool’s current installation and command documentation.

More in Codebase Architecture