Sub topic 15
Migrating an existing app one feature at a time
This chapter assumes you know TypeScript, Angular components and dependency injection, the Angular Router, and the Angular CLI. It also assumes you have read the earlier chapters on feature folders, lazy routes, barrels, path aliases, and lint rules. Here you use those pieces to move an app that is organized by file type into a feature structure, without a rewrite and without freezing development.
Why migrate incrementally
A big-bang restructure moves hundreds of files in one change. Reviewers cannot check it, merge conflicts pile up, and any regression is hard to trace to a cause. An incremental migration moves one feature per pull request. The app builds and ships after every step, and you can stop at any point with a working app.
The plan has three ideas:
- Pick one feature at a time and move it completely.
- Add boundaries (barrel, alias, lint rule) as the feature lands, so it cannot drift back.
- Tighten the lint rules gradually, so existing violations do not block unrelated work.
The starting point
A typical app organized by file type looks like this:
src/app/
components/
order-list.component.ts
order-detail.component.ts
customer-list.component.ts
services/
orders.service.ts
customers.service.ts
auth.service.ts
models/
order.model.ts
customer.model.ts
app.routes.tsEvery feature is spread across three or more folders. Any file can import any other file, so the real dependencies are hidden.
The target is the layout from earlier chapters:
src/app/
core/
shared/
orders/
data-access/
feature/
ui/
orders.routes.ts
index.ts
customers/
app.routes.tsStep 1: Prepare the ground
Do the following before you move any feature. Each item is small and independent.
- Make sure the app builds and the tests pass. You need a baseline to compare against.
- Create
core/andshared/folders, and add the path aliases totsconfig.json. Empty folders cost nothing. - Convert NgModules to standalone components where it helps. You do not need to finish this first. A feature can move while still using an NgModule internally, and you can convert it afterward.
- Install the lint tooling you will use for boundaries. In an Nx workspace this is
@nx/enforce-module-boundaries. Outside Nx, a tool such aseslint-plugin-boundariesoreslint-plugin-importrestricted paths can express similar rules.
Step 2: Pick the first feature
Choose a feature with few inbound dependencies. Count how many other files import from it. A good first candidate has these properties:
- It is a leaf. Few other features depend on it.
- It has its own route, so it can be lazy-loaded.
- It is small enough to finish in a few days.
Avoid starting with the feature everyone depends on, such as authentication. Move that one later, or treat it as core.
A quick way to measure inbound dependencies is a search for imports of the feature's files:
grep -rln "services/orders.service" src/app | sortIf many files outside the feature appear, the feature is entangled. Either choose another one, or plan to expose those files through the barrel first.
Step 3: Move the feature
Follow the same order each time, so each feature is predictable.
- Create the folder, for example
src/app/orders/, withdata-access/,feature/, andui/subfolders as needed. - Move files with
git mv, so history follows the files. Do not edit content in the same commit. - Fix imports. The compiler will list each broken path.
- Split the services. A service that serves only this feature goes into
data-access/. A service used by many features stays incore/or becomes part of a shared data-access area. - Add the feature route file with the route-scoped provider.
- Replace the eager route in
app.routes.tswithloadChildren. - Add
index.tsthat exports only what other code needs. - Replace imports from outside the feature with the alias.
A commit sequence like this keeps each commit reviewable:
git mv src/app/components/order-list.component.ts src/app/orders/feature/order-list.component.ts
git mv src/app/components/order-detail.component.ts src/app/orders/feature/order-detail.component.ts
git mv src/app/services/orders.service.ts src/app/orders/data-access/orders.store.ts
git mv src/app/models/order.model.ts src/app/orders/data-access/order.model.ts
git commit -m "Move orders files into feature folder (no content changes)"Renaming a service to a store, as above, is a content change in spirit. If you want a rename, do it in a later commit.
Switching to lazy loading
Before the move, the route table imports components directly, so they land in the main bundle:
import { Routes } from '@angular/router';
import { OrderListComponent } from './components/order-list.component';
import { OrderDetailComponent } from './components/order-detail.component';
export const routes: Routes = [
{ path: 'orders', component: OrderListComponent },
{ path: 'orders/:id', component: OrderDetailComponent },
];After the move, the app-level file only maps the prefix:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
];Check the build output after this change. The Angular CLI reports a separate lazy chunk for the feature, and the initial bundle should shrink. If it does not, something in the eager part of the app still imports the feature directly. That import is a boundary violation to fix.
Moving provider scope carefully
Old services often use providedIn: 'root'. Moving such a service to route-level providers changes its lifetime, and that can break behavior. Consider what each of these means:
- A root service is one instance for the whole app, and it lives until the page closes.
- A route-scoped service is created when the route is first activated, and it is shared by the routes under that
providersarray. Angular keeps the route's environment injector for as long as the route configuration is loaded, so state is generally kept when you navigate away and back. Do not rely on it being destroyed. - If another feature injects the service, it fails with a
NullInjectorErrorafter you removeprovidedIn: 'root'.
So scoping is not a pure refactor. Migrate in two commits: first move the file and keep providedIn: 'root'. Then, once you have confirmed that nothing outside the feature injects it, remove providedIn and add the service to the route's providers.
Step 4: Add the barrel and alias
Once the folder is in place, define the public API. Start with an empty export list and add only what the build tells you other code needs.
// src/app/orders/index.ts
export { ORDERS_ROUTES } from './orders.routes';
export type { Order } from './data-access/order.model';Then add the alias:
{
"compilerOptions": {
"paths": {
"@app/orders": ["src/app/orders/index.ts"],
"@app/shared/*": ["src/app/shared/*"]
}
}
}Fix every outside import to use @app/orders. Imports of deep files such as ../orders/data-access/orders.store now stand out, and each one is a decision. Either the symbol belongs in the public API, or the caller is reaching into something private and needs a different design, such as the communication approaches from the earlier chapter.
Step 5: Enforce the boundary
A boundary that nobody checks erodes. Once the first feature is in, add lint rules for it. Existing code probably violates many rules, so introduce them in stages:
| Stage | Rule | Effect |
|---|---|---|
| 1 | Warn on deep imports into migrated features | Shows the scale of the problem and blocks nothing |
| 2 | Error on deep imports into migrated features | New violations fail the build |
| 3 | Error on layer violations, such as `ui` importing `data-access` | Layering is enforced |
| 4 | Error on all violations, with no exceptions | Migration is complete |
Apply the rule only to features you have already migrated. Unmigrated code is exempt, so the rule can never block work on code you have not touched yet. In Nx, the tag constraints from the earlier chapter do this:
{
"@nx/enforce-module-boundaries": [
"error",
{
"depConstraints": [
{
"sourceTag": "type:feature",
"onlyDependOnLibsWithTags": ["type:ui", "type:data-access", "type:util"]
},
{
"sourceTag": "type:ui",
"onlyDependOnLibsWithTags": ["type:ui", "type:util"]
}
]
}
]
}Keep a list of known exceptions in the lint configuration, each with a comment naming the issue that will remove it. The list should only shrink.
Common problems during migration
- Circular imports. Two old services may import each other. The folder move exposes this because the barrel makes the cycle visible. Break the cycle by moving the shared part into a third file, usually in
coreorutil. - Shared models used everywhere. A model such as
Customeris often imported by many features. If it is a plain type, move it to a shared data-access area or have the owning feature export it through its barrel. Do not duplicate it. - Tests that import deep paths. Tests move with the feature, so their relative imports usually still work. Tests that import from other features should use the public API or a test double.
- Module-level singletons. An NgModule that provides services for the whole app can hide the fact that those services are used by several features. Remove the module's providers one at a time and let the compiler and tests show who depended on them.
- Stale lazy chunks. After deployment, users with an old page may request chunk file names that no longer exist. This is an existing risk with lazy loading, but it appears for the first time when you introduce it. Check how your hosting keeps previous build files.
Tracking progress
Keep a short table in the repository, such as a MIGRATION.md, and update it in each pull request:
| Feature | Folder moved | Lazy route | Barrel and alias | Lint enforced |
|---|---|---|---|---|
| orders | yes | yes | yes | yes |
| customers | yes | yes | no | no |
| reports | no | no | no | no |
This tells the team what the current state is and which rules they can rely on. It also gives a clear definition of done for each feature.
Knowing when to stop
You do not need every file in a feature folder. Code that is truly cross-cutting stays in core or shared. If the last 10 percent of the app resists the structure, and the lint rules still hold for everything else, the migration has met its goal. Judge it by outcomes: smaller initial bundle, fewer cross-feature imports, and changes that touch one folder.
Exercise
You are migrating the orders feature. OrdersService is marked providedIn: 'root', and you want it scoped to the orders routes. Describe a safe two-step order of changes and one failure you would see if you skipped the check between them.
Show answer
First commit: move the file into orders/data-access/ and keep providedIn: 'root', so behavior is unchanged. Then search for injections of the service outside the feature. Second commit: remove providedIn and add the service to the providers array on the orders route. If you skipped the search and another feature injects the service, that feature fails at runtime with a NullInjectorError, because the service is no longer in the root injector.
Exercise
After moving reports to a lazy route, the build output shows no separate chunk for it and the initial bundle has not shrunk. What is the most likely cause, and how do you find it?
Show answer
Some eagerly loaded code still imports the feature with a static import, often through its barrel or a deep path, so the bundler keeps it in the main chunk. Search for imports of reports files or @app/reports outside the feature, and replace them. The app route file must reference the feature only through import() in loadChildren. A lint rule against deep and static cross-feature imports prevents the problem from coming back.