From f4fc17b4fb880d92dd70985013dee8669dba3a87 Mon Sep 17 00:00:00 2001 From: Alex Morris Date: Thu, 19 Nov 2026 17:48:17 +0000 Subject: [PATCH] fix(core): update standalone directiveDefs and pipeDefs during HMR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In `mergeWithExistingDefinition`, `directiveDefs` and `pipeDefs` were always restored from `clone` to preserve remote scopes patched by `ɵɵsetComponentScope` from an `NgModule` file, which does not re-run during HMR of the component file. Standalone components never use `ɵɵsetComponentScope` because their imports are inlined directly onto the component definition (in `ngtsc`, `handler.ts` keeps non-self dependencies during HMR and emits the component self-reference only while used in the template). Always restoring `clone` left removed standalone directives active, caused swapped or newly added standalone directives to fail silently and pipes to throw `NG0302`, and broke recursive self-references. Use `newDef.directiveDefs` and `newDef.pipeDefs` directly for standalone components (including `null`), while keeping `clone.directiveDefs` and `clone.pipeDefs` unconditionally for non-standalone components. Add DOM-level acceptance specs in `hmr_spec.ts`. (cherry picked from commit 34c6c98f944d427ddb583e2ae511886d95256542) --- packages/core/src/render3/hmr.ts | 12 +- packages/core/test/acceptance/hmr_spec.ts | 174 +++++++++++++++++++++- 2 files changed, 174 insertions(+), 12 deletions(-) diff --git a/packages/core/src/render3/hmr.ts b/packages/core/src/render3/hmr.ts index 3a264af5a98..87ca1cbb4bf 100644 --- a/packages/core/src/render3/hmr.ts +++ b/packages/core/src/render3/hmr.ts @@ -136,11 +136,13 @@ function mergeWithExistingDefinition( // Keep the object in place, because there can be references to it, for example in the // `directiveDefs` of another definition. const replacement = Object.assign(currentDef, newDef, { - // We need to keep the existing directive and pipe defs, because they can get patched on - // by a call to `setComponentScope` from a module file. That call won't make it into the - // HMR replacement function, because it lives in an entirely different file. - directiveDefs: clone.directiveDefs, - pipeDefs: clone.pipeDefs, + // For standalone components, `setComponentScope` is never used (imports are always inlined on + // the component definition), so always take the new directive and pipe defs, including `null` + // when the last import is removed. For non-standalone components, keep the existing defs + // unconditionally, because `setComponentScope` in the module file won't run again during an + // HMR replacement of the component file. + directiveDefs: newDef.standalone ? newDef.directiveDefs : clone.directiveDefs, + pipeDefs: newDef.standalone ? newDef.pipeDefs : clone.pipeDefs, // Preserve the old `setInput` function, because it has some state. // This is fine, because the component instance is preserved as well. diff --git a/packages/core/test/acceptance/hmr_spec.ts b/packages/core/test/acceptance/hmr_spec.ts index 0e80320331a..3bd35585167 100644 --- a/packages/core/test/acceptance/hmr_spec.ts +++ b/packages/core/test/acceptance/hmr_spec.ts @@ -26,6 +26,8 @@ import { OnDestroy, OnInit, Output, + Pipe, + PipeTransform, provideZoneChangeDetection, QueryList, SimpleChanges, @@ -40,6 +42,7 @@ import { } from '../../src/core'; import {NUM_ROOT_NODES} from '../../src/hydration/interfaces'; import {ComponentType} from '../../src/render3'; +import {getComponentDef} from '../../src/render3/def_getters'; import {DEHYDRATED_VIEWS} from '../../src/render3/interfaces/container'; import {isLContainer} from '../../src/render3/interfaces/type_checks'; import {HEADER_OFFSET, TVIEW} from '../../src/render3/interfaces/view'; @@ -539,8 +542,8 @@ describe('hot module replacement', () => { it('should carry over dependencies defined by setComponentScope', () => { // In some cases the AoT compiler produces a `setComponentScope` for non-standalone - // components. We simulate it here by declaring two components that are not standalone - // and manually calling `setComponentScope`. + // components. We simulate it here by declaring two components and a pipe that are not + // standalone and manually calling `setComponentScope`. @Component({ selector: 'child-cmp', template: 'hello', @@ -548,22 +551,29 @@ describe('hot module replacement', () => { }) class ChildCmp {} + @Pipe({name: 'upperPipe', standalone: false}) + class UpperPipe implements PipeTransform { + transform(value: string): string { + return value.toUpperCase(); + } + } + @Component({ - template: 'Initial ', + template: 'Initial {{ "ok" | upperPipe }}', standalone: false, }) class RootCmp {} - ɵɵsetComponentScope(RootCmp as ComponentType, [ChildCmp], []); + ɵɵsetComponentScope(RootCmp as ComponentType, [ChildCmp], [UpperPipe]); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); - expectHTML(fixture.nativeElement, 'Initial hello'); + expectHTML(fixture.nativeElement, 'Initial hello OK'); replaceMetadata(RootCmp, { standalone: false, - template: 'Changed ', + template: 'Changed {{ "ok" | upperPipe }}', }); fixture.detectChanges(); @@ -571,7 +581,157 @@ describe('hot module replacement', () => { verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); - expectHTML(fixture.nativeElement, 'Changed hello'); + expectHTML(fixture.nativeElement, 'Changed hello OK'); + }); + + describe('directiveDefs and pipeDefs replacement', () => { + @Directive({ + selector: '[myDir]', + host: {'[attr.data-dir]': '"active"'}, + }) + class MyDirective {} + + @Directive({ + selector: '[otherDir]', + host: {'[attr.data-other]': '"other"'}, + }) + class OtherDirective {} + + @Pipe({name: 'myPipe'}) + class MyPipe implements PipeTransform { + transform(value: string): string { + return value.toUpperCase(); + } + } + + // Use a separate replacement class so JIT `depsTracker` computes a fresh standalone scope. + function hmrUpdateFrom( + target: Type, + replacement: Type, + overrides: Record = {}, + ) { + const replacementDef = getComponentDef(replacement)!; + ɵɵreplaceMetadata( + target, + (cmp: any) => { + cmp.ɵcmp = {...replacementDef, ...overrides, type: cmp}; + }, + [], + [], + null, + '', + ); + } + + it('should swap and clear standalone directives during HMR', () => { + @Component({ + selector: 'app-swap', + imports: [MyDirective], + template: '
v1
', + changeDetection: ChangeDetectionStrategy.Eager, + }) + class AppSwap {} + + @Component({ + selector: 'app-swap', + imports: [OtherDirective], + template: '
v2
', + changeDetection: ChangeDetectionStrategy.Eager, + }) + class AppSwapV2 {} + + const fixture = TestBed.createComponent(AppSwap); + fixture.detectChanges(); + let box = fixture.nativeElement.querySelector('#box'); + expect(box.getAttribute('data-dir')).toBe('active'); + expect(box.getAttribute('data-other')).toBeNull(); + + hmrUpdateFrom(AppSwap, AppSwapV2); + fixture.detectChanges(); + box = fixture.nativeElement.querySelector('#box'); + expect(box.textContent).toBe('v2'); + expect(box.getAttribute('data-dir')).toBeNull(); + expect(box.getAttribute('data-other')).toBe('other'); + + // Clearing all standalone imports (AoT omits `dependencies`, leaving `directiveDefs: null`) + // must not restore the previously active directive defs. + hmrUpdateFrom(AppSwap, AppSwapV2, { + directiveDefs: null, + pipeDefs: null, + dependencies: null, + }); + fixture.detectChanges(); + box = fixture.nativeElement.querySelector('#box'); + expect(box.getAttribute('data-dir')).toBeNull(); + expect(box.getAttribute('data-other')).toBeNull(); + }); + + it('should activate newly added directive and pipe on standalone component', () => { + @Component({ + selector: 'app-add', + imports: [], + template: '
initial
', + changeDetection: ChangeDetectionStrategy.Eager, + }) + class AppAdd {} + + @Component({ + selector: 'app-add', + imports: [MyDirective, MyPipe], + template: '
{{ "added" | myPipe }}
', + changeDetection: ChangeDetectionStrategy.Eager, + }) + class AppAddV2 {} + + const fixture = TestBed.createComponent(AppAdd); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('#box').getAttribute('data-dir')).toBeNull(); + + hmrUpdateFrom(AppAdd, AppAddV2); + fixture.detectChanges(); + const box = fixture.nativeElement.querySelector('#box'); + expect(box.getAttribute('data-dir')).toBe('active'); + expect(box.textContent).toBe('ADDED'); + }); + + it('should render recursive standalone self-reference added in HMR update', () => { + @Component({ + selector: 'app-tree', + template: '{{ label }}', + changeDetection: ChangeDetectionStrategy.Eager, + }) + class TreeNode { + @Input() label = 'root'; + @Input() child: string | null = null; + } + + // Include `TreeNode` in `imports` so JIT emits `ɵɵelementStart` (matching AoT `ngtsc`). + @Component({ + selector: 'app-tree', + imports: [TreeNode], + template: '{{ label }}@if (child) {}', + changeDetection: ChangeDetectionStrategy.Eager, + }) + class TreeNodeV2 { + @Input() label = 'root'; + @Input() child: string | null = null; + } + + // Match AoT `ngtsc` output where a non-recursive initial template omits the self-reference. + getComponentDef(TreeNode)!.directiveDefs = null; + + const fixture = TestBed.createComponent(TreeNode); + fixture.componentInstance.label = 'parent'; + fixture.componentInstance.child = 'nested-child'; + fixture.detectChanges(); + expect(fixture.nativeElement.querySelectorAll('.node').length).toBe(1); + + hmrUpdateFrom(TreeNode, TreeNodeV2, {directiveDefs: [getComponentDef(TreeNode)!]}); + fixture.detectChanges(); + const nodes = fixture.nativeElement.querySelectorAll('.node'); + expect(nodes.length).toBe(2); + expect(nodes[1].textContent).toBe('nested-child'); + }); }); describe('queries', () => {