Sub topic 14
Scaling up with workspaces and libraries
This chapter assumes you have read the earlier chapters on feature folders, lazy routes, barrels, path aliases, and layer types. You should also be comfortable with the Angular CLI, tsconfig.json, and ESLint configuration. Here you move the same ideas from folders inside one app to libraries inside a workspace.
When folders stop being enough
Feature folders with barrels and lint rules go a long way. Some signs that a single app project is no longer enough:
- Several teams work in one repository and keep touching each other's folders.
- A second app (an admin tool, a mobile shell) needs to reuse features or UI.
- Full builds and test runs take long enough that people skip them.
- Boundaries are only convention, and a barrel bypass shows up in code review every week.
A workspace addresses these problems. It is a single repository holding several projects, each with its own entry point, configuration, and tags. A library is a project that is not an app. It has a public entry file, usually src/index.ts, and other projects import only from that file.
A library is a feature folder with a harder boundary. The barrel you wrote by hand becomes the library's entry point, and the path alias becomes the library's name.
Choosing a workspace tool
You have two common choices.
| Option | What you get | Main cost |
|---|---|---|
| Angular CLI multi-project workspace | `ng generate library`, a `projects/` folder, libraries built with ng-packagr | No built-in boundary enforcement, caching, or affected-only commands |
| Nx workspace | Project tags, `@nx/enforce-module-boundaries`, a task cache, `nx affected`, a dependency graph | An extra tool to learn and keep up to date |
For a repository with several teams, Nx is the usual choice because it provides what the earlier chapters asked you to enforce. The examples below use Nx. The structure is the same with the plain CLI, but you would write the lint rules and CI filtering yourself.
Mapping features to libraries
Take the orders feature from earlier chapters. In a workspace it can be split by layer type, with one library per layer:
| Library | Layer type | Contents |
|---|---|---|
| `libs/orders/feature` | `type:feature` | Routes, smart components, `ORDERS_ROUTES` |
| `libs/orders/data-access` | `type:data-access` | `OrdersStore`, HTTP calls, `Order` model |
| `libs/orders/ui` | `type:ui` | Presentational components such as an order table |
| `libs/shared/util-format` | `type:util` | Pure functions, such as currency formatting |
The app project then shrinks to a shell. It holds the root route table, the global providers, and the bootstrap code. Everything else comes from libraries.
Generate one library with the Nx generator. Option names have changed between Nx versions, so check --help for yours.
npx nx generate @nx/angular:library \
--name=orders-feature \
--directory=libs/orders/feature \
--tags=scope:orders,type:featureThe generator creates the project, its src/index.ts, and a path alias in tsconfig.base.json. You can write the alias by hand if you are not using a generator:
{
"compilerOptions": {
"paths": {
"@shop/orders/feature": ["libs/orders/feature/src/index.ts"],
"@shop/orders/data-access": ["libs/orders/data-access/src/index.ts"],
"@shop/orders/ui": ["libs/orders/ui/src/index.ts"],
"@shop/shared/util-format": ["libs/shared/util-format/src/index.ts"]
}
}
}Use one alias per library, not a wildcard. A wildcard such as @shop/orders/* would let code import any file inside a library and defeat the entry point.
Tags and boundary rules
Each project declares tags in its project.json. Two tag dimensions work well together. type: describes the layer, and scope: describes the business area.
{
"name": "orders-feature",
"sourceRoot": "libs/orders/feature/src",
"projectType": "library",
"tags": ["scope:orders", "type:feature"]
}The lint rule reads those tags. The rule below extends the earlier example with scope constraints. A feature may depend on its own scope and on shared code. A feature in scope:orders may not import from scope:customers.
{
"overrides": [
{
"files": ["*.ts"],
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"enforceBuildableLibDependency": true,
"allow": [],
"depConstraints": [
{
"sourceTag": "type:feature",
"onlyDependOnLibsWithTags": ["type:ui", "type:data-access", "type:util"]
},
{
"sourceTag": "type:ui",
"onlyDependOnLibsWithTags": ["type:ui", "type:util"]
},
{
"sourceTag": "type:data-access",
"onlyDependOnLibsWithTags": ["type:data-access", "type:util"]
},
{
"sourceTag": "scope:orders",
"onlyDependOnLibsWithTags": ["scope:orders", "scope:shared"]
},
{
"sourceTag": "scope:customers",
"onlyDependOnLibsWithTags": ["scope:customers", "scope:shared"]
}
]
}
]
}
}
]
}A project must satisfy every constraint whose sourceTag it carries. A library tagged scope:orders and type:ui can therefore import only libraries that are both allowed by the scope rule and allowed by the type rule.
Because the rule runs in lint, a violation fails CI. The same rule also reports circular dependencies between libraries and imports that bypass an entry point, such as a relative path into another library's folder.
Lazy loading across libraries
Lazy loading still works the same way, but the import now goes through an alias. The app's route table points at the feature library:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('@shop/orders/feature').then((m) => m.ORDERS_ROUTES),
},
];Keep this the only reference to the library from the app. A second, static import of anything from @shop/orders/feature, even a type-only helper that the compiler does not erase, can pull the library into the main bundle. Nx's boundary rule reports a static import of a lazy-loaded library, so keep that check enabled.
A related gotcha is barrel size. If index.ts re-exports every file, a consumer that needs one symbol can still end up with a large chunk, and a cycle between two barrels is easy to create. Export only what other projects use.
Library kinds and build trade-offs
Libraries come in three kinds. The kind decides how the library is compiled.
| Kind | How it is compiled | Use it when |
|---|---|---|
| Non-buildable | Compiled as part of the app that imports it | Almost always, for libraries used by apps in the same repository |
| Buildable | Built on its own, and the app reuses the cached output | A large library that rarely changes and slows app builds |
| Publishable | Built as a package for npm | Other repositories consume it, so it needs a version and a changelog |
Start non-buildable. It has the least configuration, and the caching in nx build and nx test already skips unchanged projects. Move to buildable only when measured build times justify the extra setup.
Using the project graph
The workspace tool knows which projects depend on which. Two commands make the structure pay off:
npx nx graph
npx nx affected -t lint test build --base=origin/mainnx graph draws the dependency graph so you can spot unexpected edges, such as a util library depending on a feature. nx affected runs tasks only for projects changed since the base commit, plus the projects that depend on them. A change inside libs/customers/ui does not trigger tests for orders-feature unless it depends on that library.
The cache also depends on honest boundaries. If a util library secretly imports a feature, a change to that feature invalidates every project that uses the util, and the speedup disappears.
Keeping granularity sensible
Splitting too early is a common mistake. Four libraries per feature, each with its own configuration, tests, and tags, is overhead for a feature with three components. Some rules of thumb:
- Begin with a feature folder and a barrel. Extract a library when a second consumer or a second team appears.
- Split a feature into layer libraries only when the feature has enough code that the layers have different owners or different dependencies.
- Group tiny helpers into one util library per scope and avoid creating one library per function.
- Review the graph regularly. If two libraries always change together, merge them.
Migrating from folders to libraries is mechanical if the barrels already exist. Move the folder, point its alias at the new entry file, and add tags. Then turn on the lint rule and fix the violations it reports.
Exercise
Your workspace has libs/orders/ui tagged scope:orders, type:ui. A developer imports OrdersStore from @shop/orders/data-access into a component in that library. Which part of the setup stops this, and what would the developer see?
Show answer
The @nx/enforce-module-boundaries lint rule stops it. The type:ui constraint allows dependencies only on type:ui and type:util libraries, and orders/data-access is tagged type:data-access. Lint fails with a boundary violation error on that import line, and CI fails with it. The fix is to have the feature library read the store and pass data into the ui component through inputs.
Exercise
Why is a single alias such as "@shop/orders/*": ["libs/orders/*"] a poor choice compared with one alias per library entry file?
Show answer
The wildcard maps to the library folders instead of their src/index.ts files, so code can import any internal file by path. This bypasses the public entry point and makes the boundary rules unreliable. One alias per entry file means the only importable symbols are those the library exports.