Skip to content

Commit 9ddad5d

Browse files
committed
fix(@angular/build): track missing component resource paths for watch mode recovery
1 parent 0fd4404 commit 9ddad5d

5 files changed

Lines changed: 144 additions & 20 deletions

File tree

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

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -114,20 +114,27 @@ export async function compileLibrary(
114114
processWebWorker: () => '',
115115
};
116116

117-
const { referencedFiles, compilerOptions } = await compilationInstance.initialize(
118-
tsConfigPath,
119-
hostOptions,
120-
{
121-
sourcemap: true,
122-
preserveSymlinks,
123-
rootFiles,
124-
declarationMap,
125-
compilationMode,
126-
paths: entryPathsMap,
127-
cachePath: cacheOptions.enabled ? cacheOptions.path : undefined,
128-
},
129-
'library',
130-
);
117+
const { referencedFiles, compilerOptions, componentResourcesDependencies } =
118+
await compilationInstance.initialize(
119+
tsConfigPath,
120+
hostOptions,
121+
{
122+
sourcemap: true,
123+
preserveSymlinks,
124+
rootFiles,
125+
declarationMap,
126+
compilationMode,
127+
paths: entryPathsMap,
128+
cachePath: cacheOptions.enabled ? cacheOptions.path : undefined,
129+
},
130+
'library',
131+
);
132+
133+
if (componentResourcesDependencies) {
134+
for (const [containingFile, resourceFiles] of componentResourcesDependencies) {
135+
buildState.addFileReferences(containingFile, resourceFiles);
136+
}
137+
}
131138

132139
const hasStylesheetErrors = stylesheetErrors.length > 0;
133140
const emittedFiles = hasStylesheetErrors ? [] : await compilationInstance.emitAffectedFiles();

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,5 +847,53 @@ describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) =>
847847
},
848848
]);
849849
});
850+
851+
it('should recover from NG2008 when missing component templateUrl and styleUrl files are created in watch mode', async () => {
852+
await harness.writeFile(
853+
'projects/lib/src/lib/lib.component.ts',
854+
`
855+
import { Component } from '@angular/core';
856+
857+
@Component({
858+
selector: 'lib-missing-resources',
859+
templateUrl: './missing.component.html',
860+
styleUrl: './missing.component.css',
861+
})
862+
export class LibComponent {}
863+
`,
864+
);
865+
866+
harness.useTarget('build', {
867+
...BASE_OPTIONS,
868+
watch: true,
869+
});
870+
871+
await harness.executeWithCases(
872+
[
873+
async ({ result, logs }) => {
874+
expect(result?.success).toBeFalse();
875+
expect(logs).toContain(
876+
jasmine.objectContaining({
877+
level: 'error',
878+
message: jasmine.stringContaining('NG2008'),
879+
}),
880+
);
881+
882+
// Create the missing template and stylesheet files without touching lib.component.ts
883+
await harness.writeFiles({
884+
'projects/lib/src/lib/missing.component.html': '<p>Created Template</p>',
885+
'projects/lib/src/lib/missing.component.css': ':host { color: purple; }',
886+
});
887+
},
888+
({ result }) => {
889+
expect(result?.success).toBeTrue();
890+
const content = harness.readFile('dist/lib/fesm2022/lib.mjs');
891+
expect(content).toContain('Created Template');
892+
expect(content).toContain('purple');
893+
},
894+
],
895+
{ outputLogsOnFailure: false },
896+
);
897+
});
850898
});
851899
});

‎packages/angular/build/src/tools/angular/angular-host.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export interface AngularHostOptions {
1919
fileReplacements?: Record<string, string>;
2020
modifiedFiles?: Set<string>;
2121
externalStylesheets?: Map<string, string>;
22+
missingResourceFiles?: Map<string, Set<string>>;
2223
transformStylesheet(
2324
data: string,
2425
containingFile: string,
@@ -215,16 +216,25 @@ export function createAngularCompilerHost(
215216

216217
host.resourceNameToFileName = function (resourceName, containingFile) {
217218
const resolvedPath = nodePath.join(nodePath.dirname(containingFile), resourceName);
218-
if (!this.fileExists(resolvedPath)) {
219-
return null;
220-
}
221-
222219
// Reject TypeScript files used as component resources (e.g., styleUrl pointing to a .ts file).
223220
// Processing a TypeScript file as a stylesheet or template causes confusing downstream errors.
224221
if (hasTypeScriptExtension(resolvedPath)) {
225222
return null;
226223
}
227224

225+
if (!this.fileExists(resolvedPath)) {
226+
if (hostOptions.missingResourceFiles) {
227+
let missing = hostOptions.missingResourceFiles.get(containingFile);
228+
if (!missing) {
229+
missing = new Set();
230+
hostOptions.missingResourceFiles.set(containingFile, missing);
231+
}
232+
missing.add(resolvedPath);
233+
}
234+
235+
return null;
236+
}
237+
228238
// All resource names that have template file extensions are assumed to be templates
229239
// TODO: Update compiler to provide the resource type to avoid extension matching here.
230240
if (!hostOptions.externalStylesheets || hasTemplateExtension(resolvedPath)) {

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88

99
import ts from 'typescript';
10-
import type { AngularHostOptions } from '../angular-host';
10+
import { type AngularHostOptions, createAngularCompilerHost } from '../angular-host';
1111
import { CompilerOptionOverrides, transformCompilerOptions } from './compiler-options';
1212
import { TypeScriptCompilation } from './typescript-compilation';
1313
import {
@@ -480,4 +480,31 @@ describe('AngularCompilation', () => {
480480
expect(compilerOptions.composite).toBe(false);
481481
});
482482
});
483+
484+
describe('createAngularCompilerHost', () => {
485+
it('records missing non-TypeScript component resources in missingResourceFiles', () => {
486+
const missingResourceFiles = new Map<string, Set<string>>();
487+
const hostOptions: AngularHostOptions = {
488+
missingResourceFiles,
489+
transformStylesheet: async () => null,
490+
processWebWorker: (workerFile) => workerFile,
491+
};
492+
493+
const host = createAngularCompilerHost(ts, {}, hostOptions, undefined);
494+
spyOn(host, 'fileExists').and.returnValue(false);
495+
496+
expect(
497+
host.resourceNameToFileName?.('./missing.component.html', '/src/app/my.component.ts'),
498+
).toBeNull();
499+
expect(
500+
host.resourceNameToFileName?.('./missing.component.scss', '/src/app/my.component.ts'),
501+
).toBeNull();
502+
expect(host.resourceNameToFileName?.('./ignored.ts', '/src/app/my.component.ts')).toBeNull();
503+
504+
expect(Array.from(missingResourceFiles.get('/src/app/my.component.ts') ?? [])).toEqual([
505+
'/src/app/missing.component.html',
506+
'/src/app/missing.component.scss',
507+
]);
508+
});
509+
});
483510
});

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

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import assert from 'node:assert';
1111
import { relative } from 'node:path';
1212
import ts from 'typescript';
1313
import { useTypeChecking } from '../../../utils/environment-options';
14+
import { toPosixPath } from '../../../utils/path';
1415
import { profileAsync, profileSync } from '../../../utils/profiling';
1516
import {
1617
AngularHostOptions,
@@ -82,6 +83,7 @@ class AngularCompilationState {
8283
public readonly diagnosticCache = new WeakMap<ts.SourceFile, ts.Diagnostic[]>(),
8384
public readonly filesWithoutDtsSignature = new Set<string>(),
8485
public readonly useFallbackRootNames = false,
86+
public readonly missingResourceDependencies = new Map<string, Set<string>>(),
8587
) {}
8688

8789
get angularCompiler() {
@@ -134,9 +136,30 @@ export class AotCompilation extends TypeScriptCompilation {
134136
hostOptions.modifiedFiles &&
135137
hostOptions.modifiedFiles.size <= HMR_MODIFIED_FILE_LIMIT;
136138

139+
const missingResourceDependencies =
140+
this.#state?.missingResourceDependencies ?? new Map<string, Set<string>>();
141+
hostOptions.missingResourceFiles = missingResourceDependencies;
142+
137143
let staleSourceFiles;
138144
let clearPackageJsonCache = false;
139145
if (hostOptions.modifiedFiles) {
146+
for (const [containingFile, missingFiles] of missingResourceDependencies) {
147+
for (const missingFile of missingFiles) {
148+
if (
149+
hostOptions.modifiedFiles.has(missingFile) ||
150+
hostOptions.modifiedFiles.has(toPosixPath(missingFile))
151+
) {
152+
hostOptions.modifiedFiles.add(containingFile);
153+
break;
154+
}
155+
}
156+
}
157+
158+
for (const modifiedFile of hostOptions.modifiedFiles) {
159+
missingResourceDependencies.delete(modifiedFile);
160+
missingResourceDependencies.delete(toPosixPath(modifiedFile));
161+
}
162+
140163
this.invalidateFiles(hostOptions.modifiedFiles);
141164

142165
if (this.#state && hostOptions.modifiedFiles.size > 0) {
@@ -316,7 +339,15 @@ export class AotCompilation extends TypeScriptCompilation {
316339
continue;
317340
}
318341

319-
const resourceDependencies = angularCompiler.getResourceDependencies(sourceFile);
342+
const resourceDependencies = [...angularCompiler.getResourceDependencies(sourceFile)];
343+
const missingResources = missingResourceDependencies.get(sourceFile.fileName);
344+
if (missingResources) {
345+
for (const missingFile of missingResources) {
346+
if (!resourceDependencies.includes(missingFile)) {
347+
resourceDependencies.push(missingFile);
348+
}
349+
}
350+
}
320351
componentResourcesDependencies.set(sourceFile.fileName, resourceDependencies);
321352

322353
if (resourceDependencies.length === 0) {
@@ -360,6 +391,7 @@ export class AotCompilation extends TypeScriptCompilation {
360391
this.#state?.diagnosticCache,
361392
filesWithoutDtsSignature,
362393
useFallbackRootNames,
394+
missingResourceDependencies,
363395
);
364396

365397
return {

0 commit comments

Comments
 (0)