Sub topic 8
Defining a feature's public API with a barrel
This chapter assumes you can write TypeScript modules, use Angular standalone components and dependency injection, and read a route configuration. Earlier chapters laid out feature folders and lazy routes. Here you decide which files in a feature other code is allowed to import.
The problem: everything is importable
A TypeScript file can import any other file by its path. Nothing in the language marks a file as private to its folder. Suppose the orders feature contains these files:
src/app/orders/
index.ts
orders.routes.ts
data-access/
orders.store.ts
order.model.ts
feature/
order-list.component.ts
order-detail.component.ts
ui/
order-row.component.tsCode in customers can write import { OrdersStore } from '../orders/data-access/orders.store'. That works, and it creates a hidden dependency on an internal file. If the orders team renames the store or splits it in two, customers breaks. The orders team cannot tell which outside files depend on its internals without searching the whole repository.
A feature should instead have a small, deliberate public surface. Everything else is an implementation detail that can change freely.
What a barrel is
A barrel is a file, usually named index.ts, that re-exports selected symbols from other files in the same folder. Other code imports from the folder, and TypeScript resolves the import to index.ts.
// src/app/orders/index.ts
export { ORDERS_ROUTES } from './orders.routes';
export type { Order } from './data-access/order.model';This barrel exposes two things: the route definitions, so the app-level router can lazy-load the feature, and the Order type, so other features can describe an order in their own signatures. It does not export OrdersStore, OrderListComponent, or any other internal file.
A consumer now imports like this:
import type { Order } from '../orders';If the orders team moves order.model.ts into another folder, only index.ts changes.
Choosing what to export
Treat each export as a promise. Once another feature depends on a symbol, changing it costs coordination. Export the minimum.
| Candidate | Export it? | Reason |
|---|---|---|
| Route array (`ORDERS_ROUTES`) | Yes, if the app shell loads it | The shell needs it to wire up navigation |
| Model types used in other features' signatures | Yes, as types | Shared vocabulary, no runtime cost |
| Feature store | Usually no | Its providers are scoped to the feature's routes; outside code would find no instance |
| Page components | Usually no | The router loads them; nothing else should place them in a template |
| Small presentational components | Only if designed for reuse | Otherwise they belong in `shared` or stay private |
| Helper functions | Only if stable and needed elsewhere | Often a sign the helper belongs in a `util` layer |
Exporting types with `export type`
The sample barrel uses export type { Order }. This form tells the compiler the symbol is erased at runtime. It has two benefits:
- With
isolatedModulesenabled (the default in modern Angular projects), re-exporting a type with a plainexport { Order }can produce an error, because a single-file transpiler cannot tell whetherOrderis a type or a value. - The importing code cannot accidentally use the symbol as a value, and the bundler cannot treat the import as a runtime dependency on the feature.
Use export type for interfaces and type aliases. Use plain export for classes, functions, constants, and injection tokens.
Where the barrel sits
Put one barrel at the root of each feature folder. Resist adding barrels at every level.
orders/
index.ts <- public API, the only one other features use
data-access/
index.ts <- optional, internal convenience onlyInner barrels are tempting because they shorten imports inside the feature, but they have costs. They blur the distinction between public and private, since a reader sees index.ts and assumes it is a boundary. They also increase the risk of circular imports, covered below. A common rule is that only the root barrel is public, and inside the feature you import files directly by relative path.
Pitfall: circular imports
A barrel can create an import cycle. Suppose order-list.component.ts imports Order from '..' (its own feature's barrel) instead of from '../data-access/order.model'. The barrel imports orders.routes.ts, which imports order-list.component.ts, which imports the barrel. Depending on evaluation order, a value can be undefined when first used, which produces confusing errors such as a class "used before its declaration" or a decorator that sees an undefined dependency.
The rule that prevents this: code inside a feature never imports from its own barrel. The barrel is for outsiders.
Pitfall: barrels and tree-shaking
A barrel that re-exports many symbols can hurt bundle size in older toolchains, because the bundler has to analyze every re-exported module to decide what is unused. Modern Angular builds (esbuild-based, with ES modules) tree-shake re-exports well, so this is rarely a problem for a small feature barrel.
The larger concern is lazy loading. If the app shell imports a runtime value (a class or function) from the orders barrel, the bundler must include the module that defines it in the main bundle, and it can drag other modules along if they have side effects. Keep the shell's use of the barrel limited to what must be eager. Route definitions should still use dynamic import() so that the feature's code stays in its own chunk:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
];Notice that this route file imports ./orders/orders.routes directly rather than through ./orders. Importing the barrel with a static import { ORDERS_ROUTES } from './orders' would pull the routes, and everything they statically import, into the initial bundle and defeat lazy loading. If you prefer to lazy-load through the barrel, do it with a dynamic import:
loadChildren: () => import('./orders').then((m) => m.ORDERS_ROUTES),A dynamic import of the barrel is still lazy, because the whole barrel becomes one chunk.
Enforcing the barrel
A barrel is a convention. TypeScript does not stop customers from reaching into orders/data-access/.... Without enforcement, a deep import eventually appears during a rushed change, and the boundary erodes.
There are two common enforcement approaches. Both are covered in later chapters, so only the idea is shown here.
- Path aliases map a name such as
@app/ordersto the barrel, so the natural import is the correct one. - Lint rules fail the build when a file imports a deep path in another feature. In an Nx workspace,
@nx/enforce-module-boundariesdoes this; outside Nx, the ESLint ruleno-restricted-importswith a pattern such as**/orders/*/**can ban deep paths.
A minimal no-restricted-imports configuration looks like this:
{
"rules": {
"no-restricted-imports": [
"error",
{
"patterns": [
{
"group": ["**/orders/*/**"],
"message": "Import from the orders barrel, not from its internals."
}
]
}
]
}
}This pattern would also flag imports from inside the orders folder itself, so apply it through an ESLint overrides entry whose files list excludes src/app/orders/**, or use a rule set that understands feature ownership.
Versioning the public API
Because the barrel is a promise, change it deliberately:
- Adding an export is safe.
- Removing or renaming an export is a breaking change for every consumer. Search for usages first.
- Changing a type that is exported (adding a required field to
Order) affects every consumer that constructs one. - Prefer exporting narrow types. If
customersonly needs an order's id and total, defineOrderSummaryand export that. Consumers then depend on less.
Review checklist
- Each feature folder has one root
index.ts. - The barrel exports routes and the types other features truly need, and nothing else by default.
- Types are exported with
export type. - Code inside the feature does not import its own barrel.
- The app shell lazy-loads the feature with
import(). - A lint rule rejects deep imports from other features.
Exercise
The customers feature needs to show the latest order total for a customer. A teammate proposes exporting OrdersStore from the orders barrel and injecting it into CustomerDetailComponent. Give two reasons this is a poor design, and describe a better one.
Show answer
First, OrdersStore is provided in the orders route's providers, so no instance exists in the customers route subtree. Injecting it there fails at runtime with a missing-provider error. Second, exporting the store makes its whole shape (methods, signals) part of the public API, so any internal change breaks customers. A better design exports a narrow type such as OrderSummary from the barrel and gives customers its own data path: either a small root-provided OrderSummaryService exposed in the barrel that calls the orders API, or an event or shared-state mechanism from the cross-feature communication chapter. Either way, customers depends on a minimal, deliberate surface.
Exercise
A component inside orders/feature/order-list.component.ts writes import { Order } from '..' and the app begins failing with "Cannot access 'X' before initialization". What is the likely cause and the fix?
Show answer
The component imports its own feature's barrel, which creates a circular import: the barrel loads orders.routes.ts, which loads the component, which loads the barrel. Evaluation order leaves a binding uninitialized when it is first used. The fix is to import directly from the defining file, for example import type { Order } from '../data-access/order.model', and to follow the rule that code inside a feature never imports its own barrel.