Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(compiler-cli): output HMR initializer code
Adds the logic to the compiler that will output the HMR initializer code for each component, if enabled.
  • Loading branch information
crisbeto committed Oct 10, 2024
commit f6d1e52750359314749e427bb56ff2697d1e68cf
1 change: 1 addition & 0 deletions packages/bazel/src/ngc-wrapped/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export async function runOneBuild(
'onlyExplicitDeferDependencyImports',
'generateExtraImportsInLocalMode',
'_enableLetSyntax',
'_enableHmr',
]);

const userOverrides = Object.entries(userOptions)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ export function compileResults(
additionalFields: CompileResult[] | null,
deferrableImports: Set<ts.ImportDeclaration> | null,
debugInfo: Statement | null = null,
hmrInitializer: Statement | null = null,
): CompileResult[] {
const statements = def.statements;

Expand All @@ -424,6 +425,10 @@ export function compileResults(
statements.push(debugInfo);
}

if (hmrInitializer !== null) {
statements.push(hmrInitializer);
}

const results = [
fac,
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
AnimationTriggerNames,
BoundTarget,
compileClassDebugInfo,
compileClassHmrInitializer,
compileComponentClassMetadata,
compileComponentDeclareClassMetadata,
compileComponentFromMetadata,
Expand Down Expand Up @@ -179,6 +180,7 @@ import {
} from './util';
import {getTemplateDiagnostics} from '../../../typecheck';
import {JitDeclarationRegistry} from '../../common/src/jit_declaration_registry';
import {extractHmrInitializerMeta} from './hmr';

const EMPTY_ARRAY: any[] = [];

Expand Down Expand Up @@ -255,6 +257,7 @@ export class ComponentDecoratorHandler
private readonly jitDeclarationRegistry: JitDeclarationRegistry,
private readonly i18nPreserveSignificantWhitespace: boolean,
private readonly strictStandalone: boolean,
private readonly enableHmr: boolean,
) {
this.extractTemplateOptions = {
enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
Expand Down Expand Up @@ -872,6 +875,9 @@ export class ComponentDecoratorHandler
this.rootDirs,
/* forbidOrphanRenderering */ this.forbidOrphanRendering,
),
hmrInitializerMeta: this.enableHmr
? extractHmrInitializerMeta(node, this.reflector, this.rootDirs)
: null,
template,
providersRequiringFactory,
viewProvidersRequiringFactory,
Expand Down Expand Up @@ -1613,6 +1619,10 @@ export class ComponentDecoratorHandler
analysis.classDebugInfo !== null
? compileClassDebugInfo(analysis.classDebugInfo).toStmt()
: null;
const hmrInitializer =
analysis.hmrInitializerMeta !== null
? compileClassHmrInitializer(analysis.hmrInitializerMeta).toStmt()
: null;
const deferrableImports = this.deferredSymbolTracker.getDeferrableImportDecls();
return compileResults(
fac,
Expand All @@ -1622,6 +1632,7 @@ export class ComponentDecoratorHandler
inputTransformFields,
deferrableImports,
debugInfo,
hmrInitializer,
);
}

Expand Down Expand Up @@ -1695,6 +1706,10 @@ export class ComponentDecoratorHandler
analysis.classDebugInfo !== null
? compileClassDebugInfo(analysis.classDebugInfo).toStmt()
: null;
const hmrInitializer =
analysis.hmrInitializerMeta !== null
? compileClassHmrInitializer(analysis.hmrInitializerMeta).toStmt()
: null;
const deferrableImports = this.deferredSymbolTracker.getDeferrableImportDecls();
return compileResults(
fac,
Expand All @@ -1704,6 +1719,7 @@ export class ComponentDecoratorHandler
inputTransformFields,
deferrableImports,
debugInfo,
hmrInitializer,
);
}

Expand Down
43 changes: 43 additions & 0 deletions packages/compiler-cli/src/ngtsc/annotations/component/src/hmr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*!
* @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 {R3HmrInitializerMetadata, WrappedNodeExpr} from '@angular/compiler';
import {DeclarationNode, ReflectionHost} from '../../../reflection';
import {relative} from 'path';

/**
* Extracts the metadata necessary to generate an HMR initializer.
*/
export function extractHmrInitializerMeta(
clazz: DeclarationNode,
reflection: ReflectionHost,
rootDirs: readonly string[],
): R3HmrInitializerMetadata | null {
if (!reflection.isClass(clazz)) {
return null;
}

// Attempt to generate a project-relative path before falling back to the full path.
let filePath = clazz.getSourceFile().fileName;
for (const rootDir of rootDirs) {
const relativePath = relative(rootDir, filePath);
if (!relativePath.startsWith('..')) {
filePath = relativePath;
break;
}
}

const meta: R3HmrInitializerMetadata = {
type: new WrappedNodeExpr(clazz.name),
className: clazz.name.text,
timestamp: Date.now() + '',
filePath,
};

return meta;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
DeferBlockDepsEmitMode,
R3ClassDebugInfo,
R3ClassMetadata,
R3HmrInitializerMetadata,
R3ComponentMetadata,
R3DeferPerBlockDependency,
R3DeferPerComponentDependency,
Expand Down Expand Up @@ -56,6 +57,7 @@ export interface ComponentAnalysisData {
template: ParsedTemplateWithSource;
classMetadata: R3ClassMetadata | null;
classDebugInfo: R3ClassDebugInfo | null;
hmrInitializerMeta: R3HmrInitializerMetadata | null;

inputs: ClassPropertyMapping<InputMapping>;
inputFieldNamesFromMetadataArray: Set<string>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ function setup(
jitDeclarationRegistry,
/* i18nPreserveSignificantWhitespace */ true,
/* strictStandalone */ false,
/* enableHmr */ false,
);
return {reflectionHost, handler, resourceLoader, metaRegistry};
}
Expand Down
7 changes: 7 additions & 0 deletions packages/compiler-cli/src/ngtsc/core/api/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,13 @@ export interface InternalOptions {
* @internal
*/
_angularCoreVersion?: string;

/**
* Whether to enable the necessary code generation for hot module reloading.
*
* @internal
*/
_enableHmr?: boolean;
}

/**
Expand Down
3 changes: 3 additions & 0 deletions packages/compiler-cli/src/ngtsc/core/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ export class NgCompiler {
private readonly enableBlockSyntax: boolean;
private readonly enableLetSyntax: boolean;
private readonly angularCoreVersion: string | null;
private readonly enableHmr: boolean;

/**
* `NgCompiler` can be reused for multiple compilations (for resource-only changes), and each
Expand Down Expand Up @@ -462,6 +463,7 @@ export class NgCompiler {
this.enableBlockSyntax = options['_enableBlockSyntax'] ?? true;
this.enableLetSyntax = options['_enableLetSyntax'] ?? true;
this.angularCoreVersion = options['_angularCoreVersion'] ?? null;
this.enableHmr = !!options['_enableHmr'];
this.constructionDiagnostics.push(
...this.adapter.constructionDiagnostics,
...verifyCompatibleTypeCheckOptions(this.options),
Expand Down Expand Up @@ -1463,6 +1465,7 @@ export class NgCompiler {
jitDeclarationRegistry,
this.options.i18nPreserveWhitespaceForLegacyExtraction ?? true,
!!this.options.strictStandalone,
this.enableHmr,
),

// TODO(alxhub): understand why the cast here is necessary (something to do with `null`
Expand Down
63 changes: 63 additions & 0 deletions packages/compiler-cli/test/ngtsc/ngtsc_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10519,6 +10519,69 @@ runInEachFileSystem((os: string) => {
});
});

describe('HMR initializer', () => {
it('should not generate an HMR initializer by default', () => {
env.write(
'test.ts',
`
import {Component} from '@angular/core';

@Component({
selector: 'cmp',
template: 'hello',
standalone: true,
})
export class Cmp {}
`,
);

env.driveMain();

const jsContents = env.getContents('test.js');
expect(jsContents).not.toContain('import.meta.hot');
expect(jsContents).not.toContain('replaceMetadata');
});

it('should generate an HMR initializer when enabled', () => {
env.write(
'tsconfig.json',
JSON.stringify({
extends: './tsconfig-base.json',
angularCompilerOptions: {
_enableHmr: true,
},
}),
);

env.write(
'test.ts',
`
import {Component} from '@angular/core';

@Component({
selector: 'cmp',
template: 'hello',
standalone: true,
})
export class Cmp {}
`,
);

env.driveMain();

const jsContents = env.getContents('test.js');

// We need a regex match here, because the file path changes based on
// the file system and the timestamp will be different for each test run.
expect(jsContents).toMatch(
/import\.meta\.hot && import\.meta\.hot\.on\("angular:component-update", d => { if \(d\.id == ".*test\.ts%40Cmp"\) {/,
);
expect(jsContents).toMatch(
/import\("\/@ng\/component\?c=.*test\.ts%40Cmp&t=\d+"\).then\(m => i0\.ɵɵreplaceMetadata\(Cmp, m\.default\)\);/,
);
});
});

describe('tsickle compatibility', () => {
it('should preserve fileoverview comments', () => {
env.write(
Expand Down