forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(@angular/ssr): add
modulepreload
for lazy-loaded routes
Enhance performance when using SSR by adding `modulepreload` links to lazy-loaded routes. This ensures that the required modules are preloaded in the background, improving the user experience and reducing the time to interactive. Closes angular#26484
- Loading branch information
1 parent
e4448bb
commit d78d2ad
Showing
15 changed files
with
705 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.dev/license | ||
*/ | ||
|
||
import assert from 'node:assert'; | ||
import { relative } from 'node:path/posix'; | ||
import ts from 'typescript'; | ||
|
||
export function lazyRoutesTransformer( | ||
program: ts.Program, | ||
compilerHost: ts.CompilerHost, | ||
): ts.TransformerFactory<ts.SourceFile> { | ||
const compilerOptions = program.getCompilerOptions(); | ||
const moduleResolutionCache = compilerHost.getModuleResolutionCache?.(); | ||
assert( | ||
typeof compilerOptions.basePath === 'string', | ||
'compilerOptions.basePath should be a string.', | ||
); | ||
const basePath = compilerOptions.basePath; | ||
|
||
return (context: ts.TransformationContext) => { | ||
const factory = context.factory; | ||
|
||
const visitor = (node: ts.Node): ts.Node => { | ||
if (!ts.isObjectLiteralExpression(node)) { | ||
return ts.visitEachChild(node, visitor, context); | ||
} | ||
|
||
let hasPathProperty = false; | ||
let loadComponentOrChildrenProperty: ts.PropertyAssignment | undefined; | ||
for (const prop of node.properties) { | ||
if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) { | ||
continue; | ||
} | ||
|
||
const propertyNameText = prop.name.text; | ||
if (propertyNameText === 'path') { | ||
hasPathProperty = true; | ||
} else if (propertyNameText === 'loadComponent' || propertyNameText === 'loadChildren') { | ||
loadComponentOrChildrenProperty = prop; | ||
} | ||
|
||
if (hasPathProperty && loadComponentOrChildrenProperty) { | ||
break; | ||
} | ||
} | ||
|
||
const initializer = loadComponentOrChildrenProperty?.initializer; | ||
if ( | ||
!hasPathProperty || | ||
!initializer || | ||
!ts.isArrowFunction(initializer) || | ||
!ts.isCallExpression(initializer.body) || | ||
!ts.isPropertyAccessExpression(initializer.body.expression) || | ||
initializer.body.expression.name.text !== 'then' || | ||
!ts.isCallExpression(initializer.body.expression.expression) || | ||
initializer.body.expression.expression.expression.kind !== ts.SyntaxKind.ImportKeyword | ||
) { | ||
return ts.visitEachChild(node, visitor, context); | ||
} | ||
|
||
const callExpressionArgument = initializer.body.expression.expression.arguments[0]; | ||
if ( | ||
!ts.isStringLiteral(callExpressionArgument) && | ||
!ts.isNoSubstitutionTemplateLiteral(callExpressionArgument) | ||
) { | ||
return ts.visitEachChild(node, visitor, context); | ||
} | ||
|
||
const resolvedPath = ts.resolveModuleName( | ||
callExpressionArgument.text, | ||
node.getSourceFile().fileName, | ||
compilerOptions, | ||
compilerHost, | ||
moduleResolutionCache, | ||
)?.resolvedModule?.resolvedFileName; | ||
|
||
if (!resolvedPath) { | ||
return ts.visitEachChild(node, visitor, context); | ||
} | ||
|
||
const resolvedRelativePath = relative(basePath, resolvedPath); | ||
|
||
// Create the new property | ||
// Exmaple: `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" } : undefined)` | ||
const newProperty = factory.createSpreadAssignment( | ||
factory.createParenthesizedExpression( | ||
factory.createConditionalExpression( | ||
factory.createBinaryExpression( | ||
factory.createBinaryExpression( | ||
factory.createTypeOfExpression(factory.createIdentifier('ngServerMode')), | ||
factory.createToken(ts.SyntaxKind.ExclamationEqualsEqualsToken), | ||
factory.createStringLiteral('undefined'), | ||
), | ||
factory.createToken(ts.SyntaxKind.AmpersandAmpersandToken), | ||
factory.createIdentifier('ngServerMode'), | ||
), | ||
factory.createToken(ts.SyntaxKind.QuestionToken), | ||
factory.createObjectLiteralExpression( | ||
[ | ||
factory.createPropertyAssignment( | ||
factory.createIdentifier('ɵentryName'), | ||
factory.createStringLiteral(resolvedRelativePath), | ||
), | ||
], | ||
false, | ||
), | ||
factory.createToken(ts.SyntaxKind.ColonToken), | ||
factory.createIdentifier('undefined'), | ||
), | ||
), | ||
); | ||
|
||
return factory.updateObjectLiteralExpression(node, [...node.properties, newProperty]); | ||
}; | ||
|
||
return (sourceFile) => { | ||
const text = sourceFile.text; | ||
if (!text.includes('loadComponent') && !text.includes('loadChildren')) { | ||
// Fast check | ||
return sourceFile; | ||
} | ||
|
||
return ts.visitEachChild(sourceFile, visitor, context); | ||
}; | ||
}; | ||
} |
121 changes: 121 additions & 0 deletions
121
packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer_spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.dev/license | ||
*/ | ||
|
||
import ts from 'typescript'; | ||
import { lazyRoutesTransformer } from './lazy-routes-transformer'; | ||
|
||
describe('lazyRoutesTransformer', () => { | ||
let program: ts.Program; | ||
let compilerHost: ts.CompilerHost; | ||
|
||
beforeEach(() => { | ||
// Mock a basic TypeScript program and compilerHost | ||
program = ts.createProgram(['/project/src/dummy.ts'], { basePath: '/project/' }); | ||
compilerHost = { | ||
getNewLine: () => '\n', | ||
fileExists: () => true, | ||
readFile: () => '', | ||
writeFile: () => undefined, | ||
getCanonicalFileName: (fileName: string) => fileName, | ||
getCurrentDirectory: () => '/project', | ||
getDefaultLibFileName: () => 'lib.d.ts', | ||
getSourceFile: () => undefined, | ||
useCaseSensitiveFileNames: () => true, | ||
resolveModuleNames: (moduleNames, containingFile) => | ||
moduleNames.map( | ||
(name) => | ||
({ | ||
resolvedFileName: `/project/src/${name}.ts`, | ||
}) as ts.ResolvedModule, | ||
), | ||
}; | ||
}); | ||
|
||
const transformSourceFile = (sourceCode: string): ts.SourceFile => { | ||
const sourceFile = ts.createSourceFile( | ||
'/project/src/dummy.ts', | ||
sourceCode, | ||
ts.ScriptTarget.ESNext, | ||
true, | ||
ts.ScriptKind.TS, | ||
); | ||
|
||
const transformer = lazyRoutesTransformer(program, compilerHost); | ||
const result = ts.transform(sourceFile, [transformer]); | ||
|
||
return result.transformed[0]; | ||
}; | ||
|
||
it('should add ɵentryName property to object with loadComponent and path', () => { | ||
const source = ` | ||
const routes = [ | ||
{ | ||
path: 'home', | ||
loadComponent: () => import('./home').then(m => m.HomeComponent) | ||
} | ||
]; | ||
`; | ||
|
||
const transformedSourceFile = transformSourceFile(source); | ||
const transformedCode = ts.createPrinter().printFile(transformedSourceFile); | ||
|
||
expect(transformedCode).toContain( | ||
`...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" } : undefined)`, | ||
); | ||
}); | ||
|
||
it('should not modify unrelated object literals', () => { | ||
const source = ` | ||
const routes = [ | ||
{ | ||
path: 'home', | ||
component: HomeComponent | ||
} | ||
]; | ||
`; | ||
|
||
const transformedSourceFile = transformSourceFile(source); | ||
const transformedCode = ts.createPrinter().printFile(transformedSourceFile); | ||
|
||
expect(transformedCode).not.toContain(`ɵentryName`); | ||
}); | ||
|
||
it('should ignore loadComponent without a valid import call', () => { | ||
const source = ` | ||
const routes = [ | ||
{ | ||
path: 'home', | ||
loadComponent: () => someFunction() | ||
} | ||
]; | ||
`; | ||
|
||
const transformedSourceFile = transformSourceFile(source); | ||
const transformedCode = ts.createPrinter().printFile(transformedSourceFile); | ||
|
||
expect(transformedCode).not.toContain(`ɵentryName`); | ||
}); | ||
|
||
it('should resolve paths relative to basePath', () => { | ||
const source = ` | ||
const routes = [ | ||
{ | ||
path: 'about', | ||
loadChildren: () => import('./features/about').then(m => m.AboutModule) | ||
} | ||
]; | ||
`; | ||
|
||
const transformedSourceFile = transformSourceFile(source); | ||
const transformedCode = ts.createPrinter().printFile(transformedSourceFile); | ||
|
||
expect(transformedCode).toContain( | ||
`...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/features/about.ts" } : undefined)`, | ||
); | ||
}); | ||
}); |
Oops, something went wrong.