diff --git a/packages/compiler-cli/src/transformers/lower_expressions.ts b/packages/compiler-cli/src/transformers/lower_expressions.ts index 609a8bcb73..3a39e7b2e9 100644 --- a/packages/compiler-cli/src/transformers/lower_expressions.ts +++ b/packages/compiler-cli/src/transformers/lower_expressions.ts @@ -223,9 +223,19 @@ function isEligibleForLowering(node: ts.Node | undefined): boolean { // Don't lower expressions in a declaration. return false; case ts.SyntaxKind.VariableDeclaration: - // Avoid lowering expressions already in an exported variable declaration - return (ts.getCombinedModifierFlags(node as ts.VariableDeclaration) & - ts.ModifierFlags.Export) == 0; + const isExported = (ts.getCombinedModifierFlags(node as ts.VariableDeclaration) & + ts.ModifierFlags.Export) == 0; + // This might be unnecessary, as the variable might be exported and only used as a reference + // in another expression. However, the variable also might be involved in provider + // definitions. If that's the case, there is a specific token (`ROUTES`) which the compiler + // attempts to understand deeply. Sub-expressions within that token (`loadChildren` for + // example) might also require lowering even if the top-level declaration is already + // properly exported. + const varNode = node as ts.VariableDeclaration; + return isExported || (varNode.initializer !== undefined && + (ts.isObjectLiteralExpression(varNode.initializer) || + ts.isArrayLiteralExpression(varNode.initializer) || + ts.isCallExpression(varNode.initializer))); } return isEligibleForLowering(node.parent); } diff --git a/packages/compiler-cli/test/ngc_spec.ts b/packages/compiler-cli/test/ngc_spec.ts index f6b79f9e53..cc2258882a 100644 --- a/packages/compiler-cli/test/ngc_spec.ts +++ b/packages/compiler-cli/test/ngc_spec.ts @@ -875,6 +875,42 @@ describe('ngc transformer command-line', () => { expect(mymoduleSource).toMatch(/ɵ0 = .*foo\(\)/); }); + it('should lower loadChildren in an exported variable expression', () => { + write('mymodule.ts', ` + import {Component, NgModule} from '@angular/core'; + import {RouterModule} from '@angular/router'; + + export function foo(): string { + console.log('side-effect'); + return 'test'; + } + + @Component({ + selector: 'route', + template: 'route', + }) + export class Route {} + + export const routes = [ + {path: '', pathMatch: 'full', component: Route, loadChildren: foo()} + ]; + + @NgModule({ + declarations: [Route], + imports: [ + RouterModule.forRoot(routes), + ] + }) + export class MyModule {} + `); + expect(compile()).toEqual(0); + + const mymodulejs = path.resolve(outDir, 'mymodule.js'); + const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8'); + expect(mymoduleSource).toContain('loadChildren: ɵ0'); + expect(mymoduleSource).toMatch(/ɵ0 = .*foo\(\)/); + }); + it('should be able to lower supported expressions', () => { writeConfig(`{ "extends": "./tsconfig-base.json",