Skip to content

Commit 80670f5

Browse files
committed
perf(@angular/build): avoid TS AST eviction and d.ts re-emit on external resource edits
Register external stylesheet dependencies on `stylesheetFile ?? containingFile` in the library builder so modifying an external stylesheet or imported SCSS partial does not add the component `.ts` file to `effectiveModifiedFiles` and evict it from `TypeScriptCompilation`'s AST cache. Instead, `getResourceDependencies` maps the modified stylesheet back to the component `.ts` file via `resourceModifiedFiles` while reusing the cached `ts.SourceFile` AST. Additionally, persist a `WeakSet<ts.SourceFile>` of emitted declaration files on `AngularCompilationState` across incremental watch builds so that unchanged `ts.SourceFile`s re-emitted solely due to external resource edits (`templateUrl` / `styleUrl`) pass `EmitOnly.Js` to `program.emit`, skipping redundant `.d.ts` generation and downstream declaration processing.
1 parent 0fd4404 commit 80670f5

3 files changed

Lines changed: 176 additions & 6 deletions

File tree

‎packages/angular/build/src/builders/library/pipeline/compilation.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,7 @@ export async function compileLibrary(
8989
: await stylesheetBundler.bundleInline(data, containingFile);
9090

9191
if (result.referencedFiles) {
92-
buildState.addFileReferences(containingFile, result.referencedFiles);
93-
if (stylesheetFile) {
94-
buildState.addFileReferences(stylesheetFile, result.referencedFiles);
95-
}
92+
buildState.addFileReferences(stylesheetFile ?? containingFile, result.referencedFiles);
9693
}
9794

9895
if (result.warnings.length > 0) {

‎packages/angular/build/src/builders/library/tests/behavior/watch_spec.ts‎

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
*/
88

99
import { rm } from 'node:fs/promises';
10+
import { ParallelCompilation } from '../../../../tools/angular/compilation/parallel-compilation';
1011
import { executeLibraryBuilder } from '../../builder';
1112
import { CompilationMode, InlineStyleLanguage } from '../../schema';
1213
import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup';
@@ -847,5 +848,176 @@ describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) =>
847848
},
848849
]);
849850
});
851+
852+
it('should update .mjs bundle without invalidating .ts or re-emitting .d.ts when external Sass or partial is modified', async () => {
853+
await harness.writeFiles({
854+
'projects/lib/src/lib/_vars.scss': '$primary-color: rgb(10, 20, 30);',
855+
'projects/lib/src/lib/lib.component.scss':
856+
'@use "./vars"; :host { color: vars.$primary-color; padding: 4px; }',
857+
'projects/lib/src/lib/lib.component.ts': `
858+
import { Component } from '@angular/core';
859+
860+
@Component({
861+
selector: 'lib-external-sass',
862+
template: '<span>External Sass</span>',
863+
styleUrl: './lib.component.scss',
864+
})
865+
export class LibComponent {}
866+
`,
867+
});
868+
869+
const updateSpy = spyOn(ParallelCompilation.prototype, 'update').and.callThrough();
870+
const emitSpy = spyOn(ParallelCompilation.prototype, 'emitAffectedFiles').and.callThrough();
871+
872+
harness.useTarget('build', {
873+
...BASE_OPTIONS,
874+
watch: true,
875+
});
876+
877+
await harness.executeWithCases([
878+
async ({ result }) => {
879+
expect(result?.success).toBeTrue();
880+
const content = harness.readFile('dist/lib/fesm2022/lib.mjs');
881+
expect(content).toMatch(/color:\s*(?:#0a141e|rgb\(10,\s*20,\s*30\))/);
882+
expect(content).toMatch(/padding:\s*4px/);
883+
884+
updateSpy.calls.reset();
885+
emitSpy.calls.reset();
886+
887+
// Modify the external component stylesheet directly
888+
await harness.writeFile(
889+
'projects/lib/src/lib/lib.component.scss',
890+
'@use "./vars"; :host { color: vars.$primary-color; padding: 16px; }',
891+
);
892+
},
893+
async ({ result }) => {
894+
expect(result?.success).toBeTrue();
895+
const content = harness.readFile('dist/lib/fesm2022/lib.mjs');
896+
expect(content).toMatch(/color:\s*(?:#0a141e|rgb\(10,\s*20,\s*30\))/);
897+
expect(content).toMatch(/padding:\s*16px/);
898+
899+
expect(updateSpy).toHaveBeenCalledTimes(1);
900+
const updatedFilesAfterScss = [...(updateSpy.calls.mostRecent().args[0] ?? [])];
901+
expect(updatedFilesAfterScss.some((f) => f.endsWith('.ts'))).toBeFalse();
902+
903+
expect(emitSpy).toHaveBeenCalledTimes(1);
904+
const emittedAfterScss = [...(await emitSpy.calls.mostRecent().returnValue)];
905+
expect(emittedAfterScss.some((f) => f.filename.endsWith('lib.component.js'))).toBeTrue();
906+
expect(emittedAfterScss.some((f) => f.filename.endsWith('.d.ts'))).toBeFalse();
907+
908+
updateSpy.calls.reset();
909+
emitSpy.calls.reset();
910+
911+
// Modify the imported Sass partial
912+
await harness.writeFile(
913+
'projects/lib/src/lib/_vars.scss',
914+
'$primary-color: rgb(200, 100, 50);',
915+
);
916+
},
917+
async ({ result }) => {
918+
expect(result?.success).toBeTrue();
919+
const content = harness.readFile('dist/lib/fesm2022/lib.mjs');
920+
expect(content).toMatch(/color:\s*(?:#c86432|rgb\(200,\s*100,\s*50\))/);
921+
expect(content).toMatch(/padding:\s*16px/);
922+
923+
expect(updateSpy).toHaveBeenCalledTimes(1);
924+
const updatedFilesAfterPartial = [...(updateSpy.calls.mostRecent().args[0] ?? [])];
925+
expect(updatedFilesAfterPartial.some((f) => f.endsWith('.ts'))).toBeFalse();
926+
expect(updatedFilesAfterPartial.some((f) => f.endsWith('lib.component.scss'))).toBeTrue();
927+
928+
expect(emitSpy).toHaveBeenCalledTimes(1);
929+
const emittedAfterPartial = [...(await emitSpy.calls.mostRecent().returnValue)];
930+
expect(
931+
emittedAfterPartial.some((f) => f.filename.endsWith('lib.component.js')),
932+
).toBeTrue();
933+
expect(emittedAfterPartial.some((f) => f.filename.endsWith('.d.ts'))).toBeFalse();
934+
},
935+
]);
936+
});
937+
938+
it('should update .mjs bundle and report template errors without re-emitting .d.ts when external template is modified', async () => {
939+
await harness.writeFiles({
940+
'projects/lib/src/lib/lib.component.html': '<h1>{{ title }}</h1>',
941+
'projects/lib/src/lib/lib.component.ts': `
942+
import { Component } from '@angular/core';
943+
944+
@Component({
945+
selector: 'lib-external-template',
946+
templateUrl: './lib.component.html',
947+
})
948+
export class LibComponent {
949+
title = 'Hello';
950+
}
951+
`,
952+
});
953+
954+
const emitSpy = spyOn(ParallelCompilation.prototype, 'emitAffectedFiles').and.callThrough();
955+
956+
harness.useTarget('build', {
957+
...BASE_OPTIONS,
958+
watch: true,
959+
});
960+
961+
await harness.executeWithCases([
962+
async ({ result }) => {
963+
expect(result?.success).toBeTrue();
964+
expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('h1');
965+
966+
emitSpy.calls.reset();
967+
968+
// Modify external HTML template with valid markup
969+
await harness.writeFile(
970+
'projects/lib/src/lib/lib.component.html',
971+
'<section>{{ title }}</section>',
972+
);
973+
},
974+
async ({ result }) => {
975+
expect(result?.success).toBeTrue();
976+
expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('section');
977+
978+
expect(emitSpy).toHaveBeenCalledTimes(1);
979+
const emittedAfterHtml = [...(await emitSpy.calls.mostRecent().returnValue)];
980+
expect(emittedAfterHtml.some((f) => f.filename.endsWith('lib.component.js'))).toBeTrue();
981+
expect(emittedAfterHtml.some((f) => f.filename.endsWith('.d.ts'))).toBeFalse();
982+
983+
emitSpy.calls.reset();
984+
985+
// Introduce a template type-checking error in the external HTML template
986+
await harness.writeFile(
987+
'projects/lib/src/lib/lib.component.html',
988+
'<section>{{ nonExistentProp }}</section>',
989+
);
990+
},
991+
async ({ result, logs }) => {
992+
expect(result?.success).toBeFalse();
993+
expect(logs).toContain(
994+
jasmine.objectContaining({
995+
message: jasmine.stringContaining('nonExistentProp'),
996+
}),
997+
);
998+
999+
expect(emitSpy).toHaveBeenCalledTimes(1);
1000+
const emittedOnError = [...(await emitSpy.calls.mostRecent().returnValue)];
1001+
expect(emittedOnError.some((f) => f.filename.endsWith('.d.ts'))).toBeFalse();
1002+
1003+
emitSpy.calls.reset();
1004+
1005+
// Fix the external HTML template error
1006+
await harness.writeFile(
1007+
'projects/lib/src/lib/lib.component.html',
1008+
'<footer>{{ title }}</footer>',
1009+
);
1010+
},
1011+
async ({ result }) => {
1012+
expect(result?.success).toBeTrue();
1013+
expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('footer');
1014+
1015+
expect(emitSpy).toHaveBeenCalledTimes(1);
1016+
const emittedOnRecovery = [...(await emitSpy.calls.mostRecent().returnValue)];
1017+
expect(emittedOnRecovery.some((f) => f.filename.endsWith('lib.component.js'))).toBeTrue();
1018+
expect(emittedOnRecovery.some((f) => f.filename.endsWith('.d.ts'))).toBeFalse();
1019+
},
1020+
]);
1021+
});
8501022
});
8511023
});

‎packages/angular/build/src/tools/angular/compilation/aot-compilation.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ class AngularCompilationState {
8282
public readonly diagnosticCache = new WeakMap<ts.SourceFile, ts.Diagnostic[]>(),
8383
public readonly filesWithoutDtsSignature = new Set<string>(),
8484
public readonly useFallbackRootNames = false,
85+
public readonly emittedDtsSourceFiles = new WeakSet<ts.SourceFile>(),
8586
) {}
8687

8788
get angularCompiler() {
@@ -360,6 +361,7 @@ export class AotCompilation extends TypeScriptCompilation {
360361
this.#state?.diagnosticCache,
361362
filesWithoutDtsSignature,
362363
useFallbackRootNames,
364+
this.#state?.emittedDtsSourceFiles,
363365
);
364366

365367
return {
@@ -490,9 +492,9 @@ export class AotCompilation extends TypeScriptCompilation {
490492
override emitAffectedFiles(): Iterable<EmitFileResult> {
491493
assert(this.#state, 'Angular compilation must be initialized prior to emitting files.');
492494
const {
493-
affectedFiles,
494495
angularCompiler,
495496
compilerHost,
497+
emittedDtsSourceFiles,
496498
typeScriptProgram,
497499
webWorkerTransform,
498500
useTypeScriptTranspilation,
@@ -503,7 +505,6 @@ export class AotCompilation extends TypeScriptCompilation {
503505

504506
const emittedFiles = new Map<string, EmitFileResult>();
505507
const emittedSourceFiles = new Set<ts.SourceFile>();
506-
const emittedDtsSourceFiles = new Set<ts.SourceFile>();
507508
const writeFileCallback: ts.WriteFileCallback = (filename, contents, _a, _b, sourceFiles) => {
508509
if (!sourceFiles?.length && filename.endsWith(buildInfoFilename)) {
509510
// Save builder info contents to specified location

0 commit comments

Comments
 (0)