From 2f942a0370e52735bd907c6fc4d2c631375d69c8 Mon Sep 17 00:00:00 2001 From: Alan Agius <17563226+alan-agius4@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:26:05 +0000 Subject: [PATCH] perf(@angular/build): reuse inline stylesheet BundlerContext across component edits Key `#inlineContexts` in `ComponentStylesheetBundler.bundleInline()` by `path.dirname(filename)` when sourcemaps are disabled so identical inline styles across components in the same directory share a `BundlerContext`. In `ComponentStylesheetBundler.invalidate()`, call `bundler.invalidate(normalizedFiles)` on `#inlineContexts` values instead of deleting and disposing the `BundlerContext` whenever the component `.ts` file changes, preserving the `BundlerContext` (and cached output when the inline style content hash is unchanged) while still invalidating watched dependencies. --- .../esbuild/angular/component-stylesheets.ts | 24 ++-- .../angular/component-stylesheets_spec.ts | 118 ++++++++++++++++++ 2 files changed, 128 insertions(+), 14 deletions(-) create mode 100644 packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts diff --git a/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts index b5d2e453b57e..1b67247db375 100644 --- a/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts +++ b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts @@ -120,9 +120,14 @@ export class ComponentStylesheetBundler { hasher.update(data); hasher.update(externalId ?? ''); const id = hasher.digest(); - const entry = [language, id, filename].join(';'); - - const bundlerContext = await this.#inlineContexts.getOrCreate(entry, () => { + const cacheKey = [ + language, + id, + this.options.sourcemap ? filename : path.dirname(filename), + ].join(';'); + + const bundlerContext = await this.#inlineContexts.getOrCreate(cacheKey, () => { + const entry = [language, id, filename].join(';'); const namespace = 'angular:styles/component'; return new BundlerContext( @@ -212,17 +217,8 @@ export class ComponentStylesheetBundler { entries.push(entry); } } - for (const [entry, bundler] of this.#inlineContexts.entries()) { - // Entry is format: [language, id, filename].join(';') - const firstSemi = entry.indexOf(';'); - const secondSemi = firstSemi !== -1 ? entry.indexOf(';', firstSemi + 1) : -1; - const filename = secondSemi !== -1 ? entry.slice(secondSemi + 1) : ''; - if (filename && normalizedFiles.has(path.normalize(filename))) { - this.#inlineContexts.delete(entry); - void bundler.dispose().catch(() => {}); - } else { - bundler.invalidate(normalizedFiles); - } + for (const bundler of this.#inlineContexts.values()) { + bundler.invalidate(normalizedFiles); } return entries; diff --git a/packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts new file mode 100644 index 000000000000..f08b8e4ecda7 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts @@ -0,0 +1,118 @@ +/** + * @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 assert from 'node:assert'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { initializeHash } from '../../../utils/hash'; +import { BundlerContext } from '../bundler-context'; +import type { BundleStylesheetOptions } from '../stylesheets/bundle-options'; +import { ComponentStylesheetBundler } from './component-stylesheets'; + +describe('ComponentStylesheetBundler', () => { + let tempRoot: string; + + beforeAll(async () => { + await initializeHash(); + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-component-stylesheets-')); + }); + + afterAll(async () => { + if (tempRoot) { + await rm(tempRoot, { recursive: true, force: true }); + } + }); + + function createOptions( + overrides: Partial = {}, + ): BundleStylesheetOptions { + return { + workspaceRoot: tempRoot, + optimization: false, + inlineFonts: false, + sourcemap: false, + outputNames: { bundles: '[name]', media: 'media/[name]' }, + target: ['es2022'], + cacheOptions: { + enabled: false, + path: join(tempRoot, '.cache'), + basePath: tempRoot, + }, + ...overrides, + }; + } + + it('should deduplicate identical inline styles across components in the same directory when sourcemaps are disabled', async () => { + const bundler = new ComponentStylesheetBundler( + createOptions({ sourcemap: false }), + 'css', + true, + ); + const bundleSpy = spyOn(BundlerContext.prototype, 'bundle').and.callThrough(); + + try { + const compA = join(tempRoot, 'src/a.component.ts'); + const compB = join(tempRoot, 'src/b.component.ts'); + const inlineCss = ':host { color: red; }'; + + const resultA = await bundler.bundleInline(inlineCss, compA, 'css'); + const resultB = await bundler.bundleInline(inlineCss, compB, 'css'); + + expect(resultA.contents).toContain('color: red'); + expect(resultB.contents).toEqual(resultA.contents); + // Both calls share the same BundlerContext instance in #inlineContexts + expect(bundleSpy).toHaveBeenCalledTimes(2); + expect(bundleSpy.calls.first().object).toBe(bundleSpy.calls.mostRecent().object); + } finally { + await bundler.dispose(); + } + }); + + it('should not dispose inline BundlerContext on component file invalidation and should invalidate watched dependencies', async () => { + const sharedCssPath = join(tempRoot, 'shared.css'); + const compPath = join(tempRoot, 'comp.component.ts'); + await writeFile(sharedCssPath, '.shared { color: blue; }'); + + const bundler = new ComponentStylesheetBundler( + createOptions({ sourcemap: false }), + 'css', + true, + ); + const disposeSpy = spyOn(BundlerContext.prototype, 'dispose').and.callThrough(); + const invalidateSpy = spyOn(BundlerContext.prototype, 'invalidate').and.callThrough(); + + try { + const inlineCss = `@import "./shared.css"; :host { display: block; }`; + + const initialResult = await bundler.bundleInline(inlineCss, compPath, 'css'); + expect(initialResult.contents).toContain('color: blue'); + + // Invalidating the component .ts file should delegate to bundler.invalidate() without disposing the BundlerContext + bundler.invalidate([compPath]); + expect(disposeSpy).not.toHaveBeenCalled(); + expect(invalidateSpy).toHaveBeenCalledTimes(1); + + const rebuildUnchanged = await bundler.bundleInline(inlineCss, compPath, 'css'); + expect(rebuildUnchanged.contents).toContain('color: blue'); + + // Modifying and invalidating a watched dependency (@import "./shared.css") should invalidate the cached bundle result + await writeFile(sharedCssPath, '.shared { color: green; }'); + bundler.invalidate([sharedCssPath]); + expect(disposeSpy).not.toHaveBeenCalled(); + + const rebuildAfterDepChange = await bundler.bundleInline(inlineCss, compPath, 'css'); + expect(rebuildAfterDepChange.contents).toContain('color: green'); + } finally { + await bundler.dispose(); + } + + expect(disposeSpy).toHaveBeenCalledTimes(1); + }); +});