Skip to content

Commit 696d64f

Browse files
committed
perf(@angular/build): optimize library .d.ts bundling and watch compilation
- Pass `sourcemapExcludeSources: isDts` and `sourcemapIgnoreList: false` to Rolldown `bundle.generate()` so Rust omits `sourcesContent` and `x_google_ignoreList` natively. - Disable `fakeJsPlugin.generateBundle` in `bundleAllDts` and skip `\0rolldown/runtime.js` chunks in `processRolldownOutput`, avoiding materializing Rolldown's mutable `OutputBundle` proxy and mutating every `.d.ts` chunk across NAPI. - Pre-extract Rolldown chunk properties once per chunk in `processRolldownOutput` and cache `(importerDir, id)` module resolutions in `createMemoryFileLoaderPlugin`. - Forward `hostOptions.modifiedFiles` directly in `ParallelCompilation.initialize` and run `invalidateFiles` before `loadConfiguration`, eliminating a redundant worker-thread `update` RPC roundtrip on library watch rebuilds. - Cache `readConfiguration()` results in `TypeScriptCompilation.loadConfiguration` across incremental watch rebuilds until a tsconfig file, ambient declaration file, or untracked application file changes.
1 parent d3295e1 commit 696d64f

8 files changed

Lines changed: 295 additions & 101 deletions

File tree

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

Lines changed: 104 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import assert from 'node:assert';
1010
import path from 'node:path';
11-
import type { OutputChunk, Plugin, RolldownOutput, RolldownPluginOption } from 'rolldown';
11+
import type { Plugin, RolldownOutput, RolldownPluginOption } from 'rolldown';
1212
import { loadRolldown } from '../../../utils/load-rolldown';
1313
import { toPosixPath } from '../../../utils/path';
1414
import type { BundleResult, NormalizedEntryPoint, NormalizedLibraryOptions } from '../types';
@@ -372,6 +372,7 @@ function createMemoryFileLoaderPlugin(
372372
includeMap: boolean,
373373
): Plugin {
374374
const isDts = extensions === DTS_EXTENSIONS;
375+
const resolutionCache = new Map<string, { id: string; external: boolean } | null>();
375376

376377
return {
377378
name: 'memory-file-loader',
@@ -390,25 +391,48 @@ function createMemoryFileLoaderPlugin(
390391
return { id, external: true };
391392
}
392393

393-
const resolved = id[0] === '.' ? path.posix.join(path.posix.dirname(importer), id) : id;
394-
const normalizedResolved = resolved.replace(/\/+$/, '');
394+
const importerDir = path.posix.dirname(importer);
395+
const cacheKey = `${importerDir}\0${id}`;
396+
const cached = resolutionCache.get(cacheKey);
397+
if (cached !== undefined) {
398+
return cached ?? undefined;
399+
}
400+
401+
const resolved =
402+
id[0] === '.' ? path.posix.join(importerDir, id) : path.posix.normalize(id);
403+
const normalizedResolved = resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;
395404

396405
if (files.has(normalizedResolved)) {
397-
return { id: normalizedResolved, external: false };
406+
const result = { id: normalizedResolved, external: false };
407+
resolutionCache.set(cacheKey, result);
408+
409+
return result;
398410
}
399411

400-
const base = normalizedResolved.replace(/\.m?js$/, '');
412+
const base = normalizedResolved.endsWith('.js')
413+
? normalizedResolved.slice(0, -3)
414+
: normalizedResolved.endsWith('.mjs')
415+
? normalizedResolved.slice(0, -4)
416+
: normalizedResolved;
401417
if (isDts && normalizedResolved.endsWith('.mjs') && files.has(`${base}.d.mts`)) {
402-
return { id: `${base}.d.mts`, external: false };
418+
const result = { id: `${base}.d.mts`, external: false };
419+
resolutionCache.set(cacheKey, result);
420+
421+
return result;
403422
}
404423

405424
for (const ext of extensions) {
406425
const candidate = base + ext;
407426
if (files.has(candidate)) {
408-
return { id: candidate, external: false };
427+
const result = { id: candidate, external: false };
428+
resolutionCache.set(cacheKey, result);
429+
430+
return result;
409431
}
410432
}
411433

434+
resolutionCache.set(cacheKey, null);
435+
412436
return undefined;
413437
},
414438
},
@@ -426,39 +450,83 @@ function createMemoryFileLoaderPlugin(
426450
};
427451
}
428452

453+
/**
454+
* Pre-extracted metadata for a Rolldown output chunk to avoid repeated NAPI getter calls.
455+
*/
456+
interface ChunkMetadata {
457+
readonly fileName: string;
458+
readonly outputFilePath: string;
459+
readonly name: string;
460+
readonly posixModuleIds: readonly string[];
461+
readonly allImports: readonly string[];
462+
}
463+
429464
/**
430465
* Processes Rolldown output assets and chunks, extracting emitted files and computing
431466
* the transitive sets of module IDs, output file paths, and tslib imports belonging to
432467
* each entry point bundle.
433468
*
434469
* @param output The array of output chunks and assets from Rolldown.
435470
* @param dir The destination POSIX output directory prefix.
471+
* @param isDts Whether the output is for TypeScript declaration (.d.ts) bundles.
436472
* @returns The processed multi-bundle output.
437473
*/
438474
function processRolldownOutput(
439475
output: RolldownOutput['output'],
440476
dir: string,
477+
isDts: boolean,
441478
): Omit<MultiBundleOutput, 'warnings'> {
442479
const filesToEmit: MemoryOutputFile[] = [];
443480
const bundles = new Map<string, EntryBundleOutput>();
444-
const chunksByFileName = new Map<string, OutputChunk>();
481+
const chunksByFileName = new Map<string, ChunkMetadata>();
445482
const outputFileNames = new Set<string>();
446-
const entryChunks: OutputChunk[] = [];
483+
const entryChunks: ChunkMetadata[] = [];
447484

448485
for (const item of output) {
449-
outputFileNames.add(item.fileName);
450-
filesToEmit.push(
451-
createMemoryOutputFile(
452-
path.posix.join(dir, item.fileName),
453-
item.type === 'chunk' ? item.code : item.source,
454-
),
455-
);
456-
457486
if (item.type === 'chunk') {
458-
chunksByFileName.set(item.fileName, item);
459-
if (item.isEntry) {
460-
entryChunks.push(item);
487+
const moduleIds = item.moduleIds;
488+
if (isDts && moduleIds.length === 1 && moduleIds[0] === '\0rolldown/runtime.js') {
489+
continue;
490+
}
491+
492+
const fileName = item.fileName;
493+
const outputFilePath = path.posix.join(dir, fileName);
494+
outputFileNames.add(fileName);
495+
filesToEmit.push(createMemoryOutputFile(outputFilePath, item.code));
496+
497+
const posixModuleIds: string[] = [];
498+
for (const modId of moduleIds) {
499+
if (modId[0] !== '\0') {
500+
posixModuleIds.push(toPosixPath(modId));
501+
}
461502
}
503+
504+
const imports = item.imports;
505+
const dynamicImports = item.dynamicImports;
506+
const allImports =
507+
dynamicImports.length === 0
508+
? imports
509+
: imports.length === 0
510+
? dynamicImports
511+
: [...imports, ...dynamicImports];
512+
513+
const isEntry = item.isEntry;
514+
const chunkMeta: ChunkMetadata = {
515+
fileName,
516+
outputFilePath,
517+
name: isEntry ? item.name : '',
518+
posixModuleIds,
519+
allImports,
520+
};
521+
522+
chunksByFileName.set(fileName, chunkMeta);
523+
if (isEntry) {
524+
entryChunks.push(chunkMeta);
525+
}
526+
} else {
527+
const fileName = item.fileName;
528+
outputFileNames.add(fileName);
529+
filesToEmit.push(createMemoryOutputFile(path.posix.join(dir, fileName), item.source));
462530
}
463531
}
464532

@@ -467,21 +535,18 @@ function processRolldownOutput(
467535
const outputFiles = new Set<string>();
468536
let hasTslibImport = false;
469537

470-
const visited = new Set<OutputChunk>([entryChunk]);
538+
const visited = new Set<ChunkMetadata>([entryChunk]);
471539
for (const chunk of visited) {
472-
outputFiles.add(path.posix.join(dir, chunk.fileName));
473-
const mapFileName = `${chunk.fileName}.map`;
474-
if (outputFileNames.has(mapFileName)) {
475-
outputFiles.add(path.posix.join(dir, mapFileName));
540+
outputFiles.add(chunk.outputFilePath);
541+
if (outputFileNames.has(`${chunk.fileName}.map`)) {
542+
outputFiles.add(`${chunk.outputFilePath}.map`);
476543
}
477544

478-
for (const modId of chunk.moduleIds) {
479-
if (modId[0] !== '\0') {
480-
moduleIds.add(toPosixPath(modId));
481-
}
545+
for (const modId of chunk.posixModuleIds) {
546+
moduleIds.add(modId);
482547
}
483548

484-
for (const depFile of [...chunk.imports, ...chunk.dynamicImports]) {
549+
for (const depFile of chunk.allImports) {
485550
if (depFile === 'tslib') {
486551
hasTslibImport = true;
487552
}
@@ -562,12 +627,14 @@ async function executeMultiBundle(
562627
entryFileNames: `[name].${extension}`,
563628
chunkFileNames: `[name]-[hash].${extension}`,
564629
sourcemap,
630+
sourcemapExcludeSources: isDts,
631+
sourcemapIgnoreList: false,
565632
hoistTransitiveImports: false,
566633
comments: { jsdoc: isDts, legal: true, annotation: !isDts },
567634
});
568635

569636
return {
570-
...processRolldownOutput(output, dir),
637+
...processRolldownOutput(output, dir, isDts),
571638
warnings,
572639
};
573640
} finally {
@@ -637,6 +704,12 @@ async function bundleAllDts(
637704
cjsDefault: false,
638705
sideEffects: false,
639706
});
707+
// Disable `generateBundle`: Rolldown already omits sourcemaps when `sourcemap: false` and omits
708+
// `sourcesContent` in Rust via `sourcemapExcludeSources: true` when `sourcemap: true`, while
709+
// `processRolldownOutput` filters out any `\0rolldown/runtime.js` chunk directly. Disabling this
710+
// hook avoids materializing Rolldown's mutable `OutputBundle` proxy and copying every `.d.ts`
711+
// chunk across NAPI.
712+
fakeJsPlugin.generateBundle = undefined;
640713

641714
return executeMultiBundle(
642715
resolveEntryInputMap(entryPoints, true),

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

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,6 @@ export async function compileLibrary(
7171
effectiveModifiedFiles = merged;
7272
}
7373

74-
if (effectiveModifiedFiles && effectiveModifiedFiles.size > 0) {
75-
await compilationInstance.update?.(effectiveModifiedFiles);
76-
}
77-
7874
const stylesheetWarnings: PartialMessage[] = [];
7975
const stylesheetErrors: PartialMessage[] = [];
8076
const failedFiles = new Set<string>();

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,57 @@ describe('AngularCompilation', () => {
291291
expect(mockReadConfig).toHaveBeenCalledTimes(2);
292292
expect(mockReadConfig.calls.argsFor(1)[3]).toBe(passedCache);
293293
});
294+
295+
it('caches readConfiguration result across loads and invalidates when tsconfig or declaration files change', async () => {
296+
const compilation = new MockTypeScriptCompilation();
297+
const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({
298+
options: { target: ts.ScriptTarget.ES2022 },
299+
rootNames: ['/src/public-api.ts', '/src/env.d.ts'],
300+
errors: [],
301+
});
302+
spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({
303+
readConfiguration: mockReadConfig,
304+
} as unknown as typeof import('@angular/compiler-cli'));
305+
306+
await compilation.testLoadConfiguration(
307+
'/workspace/tsconfig.lib.json',
308+
{ rootFiles: ['/src/public-api.ts'] },
309+
'library',
310+
);
311+
expect(mockReadConfig).toHaveBeenCalledTimes(1);
312+
313+
// Modifying a regular .ts source file in library mode keeps the cached configuration
314+
await compilation.update?.(new Set(['/src/public-api.ts']));
315+
const secondResult = await compilation.testLoadConfiguration(
316+
'/workspace/tsconfig.lib.json',
317+
{ rootFiles: ['/src/public-api.ts', '/src/secondary.ts'] },
318+
'library',
319+
);
320+
expect(mockReadConfig).toHaveBeenCalledTimes(1);
321+
expect(secondResult.rootNames).toEqual([
322+
'/src/public-api.ts',
323+
'/src/secondary.ts',
324+
'/src/env.d.ts',
325+
]);
326+
327+
// Modifying an ambient .d.ts file invalidates the cached configuration
328+
await compilation.update?.(new Set(['/src/new-ambient.d.ts']));
329+
await compilation.testLoadConfiguration(
330+
'/workspace/tsconfig.lib.json',
331+
{ rootFiles: ['/src/public-api.ts'] },
332+
'library',
333+
);
334+
expect(mockReadConfig).toHaveBeenCalledTimes(2);
335+
336+
// Modifying the tsconfig file itself invalidates the cached configuration
337+
await compilation.update?.(new Set(['/workspace/tsconfig.lib.json']));
338+
await compilation.testLoadConfiguration(
339+
'/workspace/tsconfig.lib.json',
340+
{ rootFiles: ['/src/public-api.ts'] },
341+
'library',
342+
);
343+
expect(mockReadConfig).toHaveBeenCalledTimes(3);
344+
});
294345
});
295346

296347
describe('createAngularCompilation', () => {

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,10 @@ export class AotCompilation extends TypeScriptCompilation {
108108
// Dynamically load the Angular compiler CLI package
109109
const { NgtscProgram, OptimizeFor } = await TypeScriptCompilation.loadCompilerCli();
110110

111+
if (hostOptions.modifiedFiles) {
112+
this.invalidateFiles(hostOptions.modifiedFiles);
113+
}
114+
111115
// Load the compiler configuration and transform as needed
112116
const {
113117
compilerOptions,
@@ -138,10 +142,7 @@ export class AotCompilation extends TypeScriptCompilation {
138142

139143
let staleSourceFiles;
140144
let clearPackageJsonCache = false;
141-
if (hostOptions.modifiedFiles) {
142-
this.invalidateFiles(hostOptions.modifiedFiles);
143-
144-
if (this.#state && hostOptions.modifiedFiles.size > 0) {
145+
if (this.#state && hostOptions.modifiedFiles?.size) {
145146
for (const modifiedFile of hostOptions.modifiedFiles) {
146147
// Clear package.json cache if a node modules file was modified
147148
if (!clearPackageJsonCache && modifiedFile.includes('node_modules')) {
@@ -166,7 +167,6 @@ export class AotCompilation extends TypeScriptCompilation {
166167
this.#state.filesWithoutDtsSignature,
167168
);
168169
}
169-
}
170170
}
171171

172172
// Create Angular compiler host

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ export class JitCompilation extends TypeScriptCompilation {
4949
const { constructorParametersDownlevelTransform } =
5050
await import('@angular/compiler-cli/private/tooling');
5151

52+
if (hostOptions.modifiedFiles) {
53+
this.invalidateFiles(hostOptions.modifiedFiles);
54+
}
55+
5256
// Load the compiler configuration and transform as needed
5357
const {
5458
compilerOptions,
@@ -58,10 +62,6 @@ export class JitCompilation extends TypeScriptCompilation {
5862
tsConfigFiles,
5963
} = await this.loadConfiguration(tsconfig, compilerOptionOverrides, buildType);
6064

61-
if (hostOptions.modifiedFiles) {
62-
this.invalidateFiles(hostOptions.modifiedFiles);
63-
}
64-
6565
// Create Angular compiler host
6666
const host = createAngularCompilerHost(
6767
ts,

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ export class ParallelCompilation extends AngularCompilation {
9696
const result = await this.#worker.run(
9797
{
9898
fileReplacements: hostOptions.fileReplacements,
99+
modifiedFiles: hostOptions.modifiedFiles,
99100
tsconfig,
100101
jit: this.jit,
101102
browserOnlyBuild: this.browserOnlyBuild,

‎packages/angular/build/src/tools/angular/compilation/parallel-worker.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export interface InitRequest {
2525
browserOnlyBuild: boolean;
2626
tsconfig: string;
2727
fileReplacements?: Record<string, string>;
28+
modifiedFiles?: Set<string>;
2829
compilerOptionOverrides?: CompilerOptionOverrides;
2930
buildType?: 'application' | 'library';
3031
stylesheetPort: MessagePort;
@@ -41,7 +42,12 @@ export async function initialize(request: InitRequest): Promise<AngularCompilati
4142
activeWebWorkerPort?.close();
4243
activeWebWorkerPort = request.webWorkerPort;
4344

44-
const currentModifiedFiles = new Set(modifiedFiles);
45+
const currentModifiedFiles =
46+
modifiedFiles.size > 0 && request.modifiedFiles
47+
? new Set([...modifiedFiles, ...request.modifiedFiles])
48+
: request.modifiedFiles
49+
? new Set(request.modifiedFiles)
50+
: new Set(modifiedFiles);
4551
modifiedFiles.clear();
4652

4753
let success = false;

0 commit comments

Comments
 (0)