Skip to content

Commit da58801

Browse files
alxhubAndrewKushnir
authored andcommitted
feat(router): auto-unwrap default exports when lazy loading (#47586)
When using `loadChildren` or `loadComponent`, a common pattern is to pass a function that returns a `Promise` from a dynamic import: ```typescript { path: 'lazy', loadComponent: () => import('./lazy-file').then(m => m.LazyCmp), } ``` The `.then` part of the expression selects the particular exported component symbol from the dynamically imported ES module. ES modules can have a "default export", created with the `export default` modifier: ```typescript @component({...}) export default class LazyCmp { ... } ``` This default export is made available to dynamic imports under the well- known key of `'default'`, per the ES module spec: https://tc39.es/ecma262/#table-export-forms-mapping-to-exportentry-records This commit adds a feature to the router to automatically dereference such default exports. With this logic, when `export default` is used, a `.then` operation to select the particular exported symbol is no longer required: ```typescript { path: 'lazy', loadComponent: () => import('./lazy-file'), } ``` The above `loadComponent` operation will automatically use the `default` export of the `lazy-file` ES module. This functionality works for `loadChildren` as well. PR Close #47586
1 parent a2a066d commit da58801

9 files changed

Lines changed: 154 additions & 17 deletions

File tree

‎aio/content/guide/standalone-components.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,25 @@ export const ADMIN_ROUTES: Route[] = [
148148
];
149149
```
150150

151+
### Lazy loading and default exports
152+
153+
When using `loadChildren` and `loadComponent`, the router understands and automatically unwraps dynamic `import()` calls with `default` exports. You can take advantage of this to skip the `.then()` for such lazy loading operations.
154+
155+
```ts
156+
// In the main application:
157+
export const ROUTES: Route[] = [
158+
{path: 'admin', loadChildren: () => import('./admin/routes')},
159+
// ...
160+
];
161+
162+
// In admin/routes.ts:
163+
export default [
164+
{path: 'home', component: AdminHomeComponent},
165+
{path: 'users', component: AdminUsersComponent},
166+
// ...
167+
] as Route[];
168+
```
169+
151170
### Providing services to a subset of routes
152171

153172
The lazy loading API for `NgModule`s (`loadChildren`) creates a new "module" injector when it loads the lazily loaded children of a route. This feature was often useful to provide services only to a subset of routes in the application. For example, if all routes under `/admin` were scoped using a `loadChildren` boundary, then admin-only services could be provided only to those routes. Doing this required using the `loadChildren` API, even if lazy loading of the routes in question was unnecessary.

‎goldens/public-api/router/index.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,11 @@ export type Data = {
212212
// @public
213213
export type DebugTracingFeature = RouterFeature<RouterFeatureKind.DebugTracingFeature>;
214214

215+
// @public
216+
export interface DefaultExport<T> {
217+
default: T;
218+
}
219+
215220
// @public
216221
export class DefaultTitleStrategy extends TitleStrategy {
217222
constructor(title: Title);
@@ -359,7 +364,7 @@ export interface IsActiveMatchOptions {
359364
export type LoadChildren = LoadChildrenCallback | ɵDeprecatedLoadChildren;
360365

361366
// @public
362-
export type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Routes | Observable<Type<any> | Routes> | Promise<NgModuleFactory<any> | Type<any> | Routes>;
367+
export type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Routes | Observable<Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>> | Promise<NgModuleFactory<any> | Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>>;
363368

364369
// @public
365370
export interface Navigation {
@@ -588,7 +593,7 @@ export interface Route {
588593
component?: Type<any>;
589594
data?: Data;
590595
loadChildren?: LoadChildren;
591-
loadComponent?: () => Type<unknown> | Observable<Type<unknown>> | Promise<Type<unknown>>;
596+
loadComponent?: () => Type<unknown> | Observable<Type<unknown> | DefaultExport<Type<unknown>>> | Promise<Type<unknown> | DefaultExport<Type<unknown>>>;
592597
matcher?: UrlMatcher;
593598
outlet?: string;
594599
path?: string;

‎packages/core/test/bundling/router/bundle.golden_symbols.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1481,6 +1481,9 @@
14811481
{
14821482
"name": "matrixParamsMatch"
14831483
},
1484+
{
1485+
"name": "maybeUnwrapDefaultExport"
1486+
},
14841487
{
14851488
"name": "maybeUnwrapEmpty"
14861489
},

‎packages/router/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export {RouterLink, RouterLinkWithHref} from './directives/router_link';
1212
export {RouterLinkActive} from './directives/router_link_active';
1313
export {RouterOutlet, RouterOutletContract} from './directives/router_outlet';
1414
export {ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, Event, EventType, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationCancellationCode as NavigationCancellationCode, NavigationEnd, NavigationError, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized, Scroll} from './events';
15-
export {CanActivate, CanActivateChild, CanActivateChildFn, CanActivateFn, CanDeactivate, CanDeactivateFn, CanLoad, CanLoadFn, CanMatch, CanMatchFn, Data, LoadChildren, LoadChildrenCallback, NavigationBehaviorOptions, QueryParamsHandling, Resolve, ResolveData, ResolveFn, Route, Routes, RunGuardsAndResolvers, UrlMatcher, UrlMatchResult} from './models';
15+
export {CanActivate, CanActivateChild, CanActivateChildFn, CanActivateFn, CanDeactivate, CanDeactivateFn, CanLoad, CanLoadFn, CanMatch, CanMatchFn, Data, DefaultExport, LoadChildren, LoadChildrenCallback, NavigationBehaviorOptions, QueryParamsHandling, Resolve, ResolveData, ResolveFn, Route, Routes, RunGuardsAndResolvers, UrlMatcher, UrlMatchResult} from './models';
1616
export {DefaultTitleStrategy, TitleStrategy} from './page_title_strategy';
1717
export {DebugTracingFeature, DisabledInitialNavigationFeature, EnabledBlockingInitialNavigationFeature, InitialNavigationFeature, InMemoryScrollingFeature, PreloadingFeature, provideRouter, provideRoutes, RouterConfigurationFeature, RouterFeature, RouterFeatures, withDebugTracing, withDisabledInitialNavigation, withEnabledBlockingInitialNavigation, withInMemoryScrolling, withPreloading, withRouterConfig} from './provide_router';
1818
export {BaseRouteReuseStrategy, DetachedRouteHandle, RouteReuseStrategy} from './route_reuse_strategy';

‎packages/router/src/models.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,22 @@ export type ResolveData = {
8989
[key: string|symbol]: any|ResolveFn<unknown>
9090
};
9191

92+
/**
93+
* An ES Module object with a default export of the given type.
94+
*
95+
* @see `Route#loadComponent`
96+
* @see `LoadChildrenCallback`
97+
*
98+
* @publicApi
99+
*/
100+
export interface DefaultExport<T> {
101+
/**
102+
* Default exports are bound under the name `"default"`, per the ES Module spec:
103+
* https://tc39.es/ecma262/#table-export-forms-mapping-to-exportentry-records
104+
*/
105+
default: T;
106+
}
107+
92108
/**
93109
*
94110
* A function that is called to resolve a collection of lazy-loaded routes.
@@ -113,11 +129,19 @@ export type ResolveData = {
113129
* }];
114130
* ```
115131
*
132+
* If the lazy-loaded routes are exported via a `default` export, the `.then` can be omitted:
133+
* ```
134+
* [{
135+
* path: 'lazy',
136+
* loadChildren: () => import('./lazy-route/lazy.routes'),
137+
* }];
138+
*
116139
* @see [Route.loadChildren](api/router/Route#loadChildren)
117140
* @publicApi
118141
*/
119142
export type LoadChildrenCallback = () => Type<any>|NgModuleFactory<any>|Routes|
120-
Observable<Type<any>|Routes>|Promise<NgModuleFactory<any>|Type<any>|Routes>;
143+
Observable<Type<any>|Routes|DefaultExport<Type<any>>|DefaultExport<Routes>>|
144+
Promise<NgModuleFactory<any>|Type<any>|Routes|DefaultExport<Type<any>>|DefaultExport<Routes>>;
121145

122146
/**
123147
*
@@ -439,7 +463,8 @@ export interface Route {
439463
/**
440464
* An object specifying a lazy-loaded component.
441465
*/
442-
loadComponent?: () => Type<unknown>| Observable<Type<unknown>>| Promise<Type<unknown>>;
466+
loadComponent?: () => Type<unknown>| Observable<Type<unknown>|DefaultExport<Type<unknown>>>|
467+
Promise<Type<unknown>|DefaultExport<Type<unknown>>>;
443468
/**
444469
* Filled for routes `loadComponent` once the component is loaded.
445470
* @internal

‎packages/router/src/router_config_loader.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {ConnectableObservable, from, Observable, of, Subject} from 'rxjs';
1111
import {catchError, finalize, map, mergeMap, refCount, tap} from 'rxjs/operators';
1212

1313
import {deprecatedLoadChildrenString} from './deprecated_load_children';
14-
import {LoadChildren, LoadChildrenCallback, LoadedRouterConfig, Route, Routes} from './models';
14+
import {DefaultExport, LoadChildren, LoadChildrenCallback, LoadedRouterConfig, Route, Routes} from './models';
1515
import {flatten, wrapIntoObservable} from './utils/collection';
1616
import {assertStandalone, standardizeConfig, validateConfig} from './utils/config';
1717

@@ -56,6 +56,7 @@ export class RouterConfigLoader {
5656
}
5757
const loadRunner = wrapIntoObservable(route.loadComponent!())
5858
.pipe(
59+
map(maybeUnwrapDefaultExport),
5960
tap(component => {
6061
if (this.onLoadEndListener) {
6162
this.onLoadEndListener(route);
@@ -127,13 +128,29 @@ export class RouterConfigLoader {
127128
if (deprecatedResult) {
128129
return deprecatedResult;
129130
}
130-
131-
return wrapIntoObservable((loadChildren as LoadChildrenCallback)()).pipe(mergeMap((t) => {
132-
if (t instanceof NgModuleFactory || Array.isArray(t)) {
133-
return of(t);
134-
} else {
135-
return from(this.compiler.compileModuleAsync(t));
136-
}
137-
}));
131+
return wrapIntoObservable((loadChildren as LoadChildrenCallback)())
132+
.pipe(
133+
map(maybeUnwrapDefaultExport),
134+
mergeMap((t) => {
135+
if (t instanceof NgModuleFactory || Array.isArray(t)) {
136+
return of(t);
137+
} else {
138+
return from(this.compiler.compileModuleAsync(t));
139+
}
140+
}),
141+
);
138142
}
139143
}
144+
145+
function isWrappedDefaultExport<T>(value: T|DefaultExport<T>): value is DefaultExport<T> {
146+
// We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be
147+
// dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that
148+
// `default` will be a renamed property.
149+
return value && typeof value === 'object' && 'default' in value;
150+
}
151+
152+
function maybeUnwrapDefaultExport<T>(input: T|DefaultExport<T>): T {
153+
// As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not
154+
// subject to property renaming, so we reference it with bracket access.
155+
return isWrappedDefaultExport(input) ? input['default'] : input;
156+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {Component} from '@angular/core';
10+
11+
@Component({
12+
standalone: true,
13+
template: 'default exported',
14+
selector: 'test-route',
15+
})
16+
export default class TestRoute {
17+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {Component} from '@angular/core';
10+
import {Routes} from '@angular/router';
11+
12+
@Component({
13+
standalone: true,
14+
template: 'default exported',
15+
selector: 'test-route',
16+
})
17+
export class TestRoute {
18+
}
19+
20+
21+
export default [
22+
{path: '', pathMatch: 'full', component: TestRoute},
23+
] as Routes;

‎packages/router/test/standalone.spec.ts‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,9 @@
99
import {Component, Injectable, NgModule} from '@angular/core';
1010
import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
1111
import {By} from '@angular/platform-browser';
12-
import {Router} from '@angular/router';
12+
import {NavigationEnd, Router, RouterModule} from '@angular/router';
1313
import {RouterTestingModule} from '@angular/router/testing';
14-
15-
import {RouterModule} from '../src';
14+
import {filter, first} from 'rxjs/operators';
1615

1716
@Component({template: '<div>simple standalone</div>', standalone: true})
1817
export class SimpleStandaloneComponent {
@@ -340,6 +339,35 @@ describe('standalone in Router API', () => {
340339
expect(() => advance(root)).toThrowError(/.*home.*component must be standalone/);
341340
}));
342341
});
342+
describe('default export unwrapping', () => {
343+
it('should work for loadComponent', async () => {
344+
TestBed.configureTestingModule({
345+
imports: [RouterTestingModule.withRoutes([{
346+
path: 'home',
347+
loadComponent: () => import('./default_export_component'),
348+
}])],
349+
});
350+
351+
const root = TestBed.createComponent(RootCmp);
352+
await TestBed.inject(Router).navigateByUrl('/home');
353+
354+
expect(root.nativeElement.innerHTML).toContain('default exported');
355+
});
356+
357+
it('should work for loadChildren', async () => {
358+
TestBed.configureTestingModule({
359+
imports: [RouterTestingModule.withRoutes([{
360+
path: 'home',
361+
loadChildren: () => import('./default_export_routes'),
362+
}])],
363+
});
364+
365+
const root = TestBed.createComponent(RootCmp);
366+
await TestBed.inject(Router).navigateByUrl('/home');
367+
368+
expect(root.nativeElement.innerHTML).toContain('default exported');
369+
});
370+
});
343371
});
344372

345373
function advance(fixture: ComponentFixture<unknown>) {

0 commit comments

Comments
 (0)