Sub topic 9
Importing features through path aliases
This chapter covers TypeScript path aliases and how they work with feature barrels. It assumes you can read TypeScript, know Angular dependency injection and the router, and have used the Angular CLI. You should already have a feature folder with a barrel file (index.ts) that lists its public API. The aliases below build on that barrel.
The problem aliases solve
Without aliases, code that reaches into another feature uses relative paths:
import { Order } from '../../../orders/data-access/order.model';This line has three problems:
- It breaks when either file moves, because the number of
../segments changes. - It bypasses the barrel. Nothing stops you from importing
data-access/order.modeldirectly, even though the barrel exists to hide that path. - It is hard to read. You can't tell at a glance whether the import is from your own feature or from another one.
A path alias gives a feature a stable name. The import becomes:
import type { Order } from '@app/orders';The alias resolves to the barrel file, so the import goes through the public API. If you later move the internals of orders, only the alias target or the barrel changes. Consumers stay as they are.
Configuring paths in tsconfig.json
Aliases are set in the compilerOptions.paths map of tsconfig.json. Each key is the alias. Each value is an array of file locations, which TypeScript tries in order.
{
"compilerOptions": {
"paths": {
"@app/orders": ["src/app/orders/index.ts"],
"@app/shared/*": ["src/app/shared/*"]
}
}
}There are two kinds of entry here:
@app/ordersis an exact alias. It maps one name to one file, the barrel. This is the right form for a feature, because it allows exactly one entry point.@app/shared/*is a wildcard alias. The*matches any text and is substituted into the target.@app/shared/buttonresolves tosrc/app/shared/button.
Depending on your TypeScript version and setup, you may also need baseUrl. Since TypeScript 4.1, paths can work without baseUrl, and then the targets are resolved relative to the tsconfig.json file. If your project sets baseUrl: ".", the targets are resolved from that folder instead. Angular CLI projects usually have baseUrl set in tsconfig.json already. Keep whichever the project uses and write targets relative to it.
Where to put the configuration
A new Angular CLI project has a root tsconfig.json and separate tsconfig.app.json and tsconfig.spec.json files that extend it. Put paths in the root file. Both the application build and the unit tests then see the same aliases. If you set paths in a child file, it replaces the parent's paths entirely. TypeScript does not merge the two maps.
Exact aliases or wildcards
The choice between the two forms is a design decision. It decides how much of a feature other code can reach.
| Alias form | Example | What consumers can import | Typical use |
|---|---|---|---|
| Exact | `@app/orders` | Only what the barrel exports | Feature folders |
| Wildcard | `@app/orders/*` | Any file under the folder | Shared utilities where every file is public |
A wildcard on a feature, such as @app/orders/*, undoes the barrel. Any consumer can write @app/orders/data-access/orders.store and take an internal file. Use exact aliases for features. Use wildcards only for folders like shared, where each file is meant to be imported on its own.
A complete example
Suppose a customers feature needs the Order type to show a customer's recent orders. It imports through the alias:
import { Component, input } from '@angular/core';
import type { Order } from '@app/orders';
@Component({
selector: 'app-customer-orders',
standalone: true,
template: `
<ul>
@for (order of orders(); track order.id) {
<li>{{ order.id }}</li>
}
</ul>
`,
})
export class CustomerOrdersComponent {
readonly orders = input.required<Order[]>();
}Here the component gets only a type. The barrel exports Order with export type, so it is erased at compile time and creates no runtime link between the two features' bundles. That matters for lazy loading, which the next section covers.
The matching barrel stays as in the earlier chapter:
// src/app/orders/index.ts
export { ORDERS_ROUTES } from './orders.routes';
export type { Order } from './data-access/order.model';Aliases and lazy loading
A barrel can quietly defeat lazy loading. Look at what index.ts exports: ORDERS_ROUTES, which is a value. If another feature writes a normal import of a value from @app/orders, the bundler follows that import and pulls the orders routes file into the importing bundle. The routes file references the lazy components only through import() calls, so those stay split. But anything else the barrel re-exports as a value, such as a store or a component, is now part of the consumer's chunk.
Follow these rules to avoid this:
- Keep the barrel small. Export only what other features need.
- Prefer
export typeandimport typefor shapes shared across features. They leave no code behind. - Load features through the router, with
loadChildrenand a dynamicimport(). The app routes file can use the alias there:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () => import('@app/orders').then((m) => m.ORDERS_ROUTES),
},
];A dynamic import('@app/orders') goes through the barrel and still splits into a separate chunk. Only the routes file is needed to start the feature, and the barrel does not export anything heavier.
How the tooling resolves aliases
TypeScript uses paths for type checking and editor features such as go-to-definition. It does not rewrite import strings in the output. The build tool has to resolve them too. The Angular CLI reads paths from the TypeScript configuration, so ng build and ng serve work with no extra setup.
Other tools do not always read it automatically:
- Unit test runners need their own mapping when they don't go through the Angular builder. Jest, for example, needs
moduleNameMapperentries or a helper that convertspaths. The Angular CLI's own test builder handles this for you. - ESLint rules that check import boundaries need to resolve the alias to a real file. Nx's rule does this by reading the TypeScript configuration.
- Scripts run with plain Node, such as a seed script, will fail to resolve
@app/ordersunless a tool liketsxortsconfig-pathsis used.
If an alias works in the editor but fails in one tool, the cause is nearly always that tool's resolver. Check the tool's configuration before changing the aliases.
Choosing alias names
Pick a naming scheme and keep it:
- Use one prefix for the app, such as
@app/. It separates your code from npm packages, which also use@scope/names. - Name the alias after the feature, not its location.
@app/ordersis better than@app/features/orders, which would need a change if the folder moved. - Avoid a prefix that matches a real npm scope. If you name an alias
@angular/orders, tools may look for it innode_modules.
In a workspace of libraries, the same idea applies, and the tooling often generates the aliases. The naming rule stays the same.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module '@app/orders'` in the editor only | The editor uses a different tsconfig than the one holding `paths` | Put `paths` in the root `tsconfig.json` and restart the TypeScript server |
| The build works but unit tests fail to resolve the alias | The test runner has its own resolver | Map the aliases in the runner's configuration |
| Aliases vanish in `tsconfig.app.json` | A child config defines its own `paths`, which replaces the parent's | Define `paths` once, in the root file |
| A lazy feature's code appears in the main bundle | A static value import of the barrel | Use `import type` or a dynamic `import()` |
| Circular import warning between two features | Two barrels import each other | Move the shared type to a lower layer, such as a util or shared folder |
| Wrong file is picked up | Two aliases overlap, for example `@app/*` and `@app/orders` | TypeScript prefers the longest matching prefix. Check for overlaps and remove the broader one |
Visualizing the import path
The diagram shows how an import in one feature reaches another feature only through the alias and the barrel.
Summary checklist
- Define aliases in the root
tsconfig.json, once. - Use an exact alias per feature, pointing at its barrel.
- Use wildcards only for folders where every file is public.
- Share types with
export typeandimport type. - Load whole features with
import()through the router. - Check that each tool in the chain, such as the test runner, resolves the aliases.
Exercise
The orders feature has index.ts as its barrel. A teammate adds the alias "@app/orders/*": ["src/app/orders/*"] to tsconfig.json so that customers can import @app/orders/data-access/orders.store. Name two problems with this change and give the alias configuration you would use instead.
Show answer
First, the wildcard exposes every file in the orders folder, so the barrel no longer defines the feature's public API and other features can depend on internal files such as the store. Second, a static import of the store from customers puts the store, and what it imports, in the customers chunk and can defeat lazy loading of orders. Use the exact alias "@app/orders": ["src/app/orders/index.ts"]. If customers needs data from orders, export only what is needed from the barrel, preferably as export type.
Exercise
Your unit tests run through Jest directly and report Cannot find module '@app/shared/button', but ng build succeeds. What is the most likely cause, and where do you fix it?
Show answer
TypeScript and the Angular CLI builder read paths from tsconfig.json, but Jest has its own module resolver and does not read it automatically. Add a moduleNameMapper entry in the Jest configuration, for example mapping ^@app/shared/(.*)$ to <rootDir>/src/app/shared/$1, or use a helper that generates the mapper from the paths in tsconfig.