Skip to content

Commit 2f942a0

Browse files
committed
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.
1 parent 0fd4404 commit 2f942a0

2 files changed

Lines changed: 128 additions & 14 deletions

File tree

‎packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,14 @@ export class ComponentStylesheetBundler {
120120
hasher.update(data);
121121
hasher.update(externalId ?? '');
122122
const id = hasher.digest();
123-
const entry = [language, id, filename].join(';');
124-
125-
const bundlerContext = await this.#inlineContexts.getOrCreate(entry, () => {
123+
const cacheKey = [
124+
language,
125+
id,
126+
this.options.sourcemap ? filename : path.dirname(filename),
127+
].join(';');
128+
129+
const bundlerContext = await this.#inlineContexts.getOrCreate(cacheKey, () => {
130+
const entry = [language, id, filename].join(';');
126131
const namespace = 'angular:styles/component';
127132

128133
return new BundlerContext(
@@ -212,17 +217,8 @@ export class ComponentStylesheetBundler {
212217
entries.push(entry);
213218
}
214219
}
215-
for (const [entry, bundler] of this.#inlineContexts.entries()) {
216-
// Entry is format: [language, id, filename].join(';')
217-
const firstSemi = entry.indexOf(';');
218-
const secondSemi = firstSemi !== -1 ? entry.indexOf(';', firstSemi + 1) : -1;
219-
const filename = secondSemi !== -1 ? entry.slice(secondSemi + 1) : '';
220-
if (filename && normalizedFiles.has(path.normalize(filename))) {
221-
this.#inlineContexts.delete(entry);
222-
void bundler.dispose().catch(() => {});
223-
} else {
224-
bundler.invalidate(normalizedFiles);
225-
}
220+
for (const bundler of this.#inlineContexts.values()) {
221+
bundler.invalidate(normalizedFiles);
226222
}
227223

228224
return entries;
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import assert from 'node:assert';
10+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
11+
import { join } from 'node:path';
12+
import { initializeHash } from '../../../utils/hash';
13+
import { BundlerContext } from '../bundler-context';
14+
import type { BundleStylesheetOptions } from '../stylesheets/bundle-options';
15+
import { ComponentStylesheetBundler } from './component-stylesheets';
16+
17+
describe('ComponentStylesheetBundler', () => {
18+
let tempRoot: string;
19+
20+
beforeAll(async () => {
21+
await initializeHash();
22+
const baseTmpDir = process.env['TEST_TMPDIR'];
23+
assert(baseTmpDir, 'TEST_TMPDIR is not set');
24+
tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-component-stylesheets-'));
25+
});
26+
27+
afterAll(async () => {
28+
if (tempRoot) {
29+
await rm(tempRoot, { recursive: true, force: true });
30+
}
31+
});
32+
33+
function createOptions(
34+
overrides: Partial<BundleStylesheetOptions> = {},
35+
): BundleStylesheetOptions {
36+
return {
37+
workspaceRoot: tempRoot,
38+
optimization: false,
39+
inlineFonts: false,
40+
sourcemap: false,
41+
outputNames: { bundles: '[name]', media: 'media/[name]' },
42+
target: ['es2022'],
43+
cacheOptions: {
44+
enabled: false,
45+
path: join(tempRoot, '.cache'),
46+
basePath: tempRoot,
47+
},
48+
...overrides,
49+
};
50+
}
51+
52+
it('should deduplicate identical inline styles across components in the same directory when sourcemaps are disabled', async () => {
53+
const bundler = new ComponentStylesheetBundler(
54+
createOptions({ sourcemap: false }),
55+
'css',
56+
true,
57+
);
58+
const bundleSpy = spyOn(BundlerContext.prototype, 'bundle').and.callThrough();
59+
60+
try {
61+
const compA = join(tempRoot, 'src/a.component.ts');
62+
const compB = join(tempRoot, 'src/b.component.ts');
63+
const inlineCss = ':host { color: red; }';
64+
65+
const resultA = await bundler.bundleInline(inlineCss, compA, 'css');
66+
const resultB = await bundler.bundleInline(inlineCss, compB, 'css');
67+
68+
expect(resultA.contents).toContain('color: red');
69+
expect(resultB.contents).toEqual(resultA.contents);
70+
// Both calls share the same BundlerContext instance in #inlineContexts
71+
expect(bundleSpy).toHaveBeenCalledTimes(2);
72+
expect(bundleSpy.calls.first().object).toBe(bundleSpy.calls.mostRecent().object);
73+
} finally {
74+
await bundler.dispose();
75+
}
76+
});
77+
78+
it('should not dispose inline BundlerContext on component file invalidation and should invalidate watched dependencies', async () => {
79+
const sharedCssPath = join(tempRoot, 'shared.css');
80+
const compPath = join(tempRoot, 'comp.component.ts');
81+
await writeFile(sharedCssPath, '.shared { color: blue; }');
82+
83+
const bundler = new ComponentStylesheetBundler(
84+
createOptions({ sourcemap: false }),
85+
'css',
86+
true,
87+
);
88+
const disposeSpy = spyOn(BundlerContext.prototype, 'dispose').and.callThrough();
89+
const invalidateSpy = spyOn(BundlerContext.prototype, 'invalidate').and.callThrough();
90+
91+
try {
92+
const inlineCss = `@import "./shared.css"; :host { display: block; }`;
93+
94+
const initialResult = await bundler.bundleInline(inlineCss, compPath, 'css');
95+
expect(initialResult.contents).toContain('color: blue');
96+
97+
// Invalidating the component .ts file should delegate to bundler.invalidate() without disposing the BundlerContext
98+
bundler.invalidate([compPath]);
99+
expect(disposeSpy).not.toHaveBeenCalled();
100+
expect(invalidateSpy).toHaveBeenCalledTimes(1);
101+
102+
const rebuildUnchanged = await bundler.bundleInline(inlineCss, compPath, 'css');
103+
expect(rebuildUnchanged.contents).toContain('color: blue');
104+
105+
// Modifying and invalidating a watched dependency (@import "./shared.css") should invalidate the cached bundle result
106+
await writeFile(sharedCssPath, '.shared { color: green; }');
107+
bundler.invalidate([sharedCssPath]);
108+
expect(disposeSpy).not.toHaveBeenCalled();
109+
110+
const rebuildAfterDepChange = await bundler.bundleInline(inlineCss, compPath, 'css');
111+
expect(rebuildAfterDepChange.contents).toContain('color: green');
112+
} finally {
113+
await bundler.dispose();
114+
}
115+
116+
expect(disposeSpy).toHaveBeenCalledTimes(1);
117+
});
118+
});

0 commit comments

Comments
 (0)