Skip to content

Commit 746b351

Browse files
committed
fix(@angular/build): disable code splitting for unit test builds
Every spec file is its own entry point, so esbuild code splitting hoists any module reached from more than one spec into a chunk shared between them. A module placed in a shared chunk is wrapped in a lazy `__esm` initializer, so its exported value is only assigned once that initializer runs, and importing chunks read the export as a live ESM binding. The unit test runners load the generated output through a module runner rather than the browser's own ESM implementation, and that does not reliably preserve those bindings. An importing chunk can therefore observe the export as `undefined`. A component whose class field initializer reads a `const` exported from a module that was hoisted into a shared chunk fails with a `TypeError`, while the same value read later, or read from within the shared chunk itself, is correct. It only appears once a project has more than one spec file, because a single entry point inlines everything and never splits. Test bundles are never downloaded by a browser, so splitting has nothing to optimize here. This disables it for the unit test build only, via an internal option, leaving application builds unaffected. The regression test mirrors the reproduction's exact shape: a shared const read during class-field initialization from a spec with an async test callback, under zone.js polyfills. That combination is load-bearing: zone.js downlevels async, the spec then imports the `__async` helper, and esbuild emits the spec entry CommonJS-wrapped with the component module behind a lazy `__esm` initializer. The fixture file set was verified to fail against an unpatched 21.2.19 build and pass with this change applied.
1 parent 3039776 commit 746b351

4 files changed

Lines changed: 200 additions & 0 deletions

File tree

packages/angular/build/src/builders/application/options.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,20 @@ interface InternalOptions {
126126
* Suppress build summary and stats table.
127127
*/
128128
quiet?: boolean;
129+
130+
/**
131+
* Disables esbuild code splitting for the browser code bundle.
132+
*
133+
* Splitting emits shared chunks whose exports are read across chunk boundaries as live ESM
134+
* bindings. A module hoisted into a shared chunk is wrapped in a lazy initializer, so its exported
135+
* value is only assigned once that initializer runs. Runners that load the generated output
136+
* through a module runner rather than the browser's own ESM implementation do not reliably
137+
* preserve those bindings, and an importing chunk can observe the export as `undefined`.
138+
*
139+
* Test bundles are never downloaded by a browser, so there is nothing for splitting to optimize
140+
* there. Used exclusively for tests and shouldn't be used for other kinds of builds.
141+
*/
142+
disableCodeSplitting?: boolean;
129143
}
130144

131145
/** Full set of options for `application` builder. */
@@ -439,6 +453,7 @@ export async function normalizeOptions(
439453
partialSSRBuild = false,
440454
externalRuntimeStyles,
441455
instrumentForCoverage,
456+
disableCodeSplitting,
442457
} = options;
443458

444459
// Return all the normalized options
@@ -475,6 +490,7 @@ export async function normalizeOptions(
475490
watch,
476491
workspaceRoot,
477492
entryPoints,
493+
disableCodeSplitting,
478494
optimizationOptions,
479495
outputOptions,
480496
outExtension,

packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,12 @@ export async function getVitestBuildOptions(
257257
outputHashing: adjustOutputHashing(baseBuildOptions.outputHashing),
258258
optimization: false,
259259
entryPoints,
260+
// Every spec file is its own entry point, so splitting hoists any module shared between two
261+
// specs into a chunk whose exports are then read across a chunk boundary. Those reads rely on
262+
// live ESM bindings, and a module placed in a shared chunk is only assigned its exported value
263+
// when that chunk's lazy initializer runs, so an importing chunk can read `undefined`. Nothing
264+
// downloads these bundles, so there is no benefit to weigh against that.
265+
disableCodeSplitting: true,
260266
// Enable support for vitest browser prebundling. Excludes can be controlled with a runnerConfig
261267
// and the `optimizeDeps.exclude` option.
262268
externalPackages: true,
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
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 { execute } from '../../index';
10+
import {
11+
BASE_OPTIONS,
12+
describeBuilder,
13+
UNIT_TEST_BUILDER_INFO,
14+
setupApplicationTarget,
15+
} from '../setup';
16+
17+
describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => {
18+
describe('Behavior: "Vitest shared chunk initialization"', () => {
19+
// Regression test for https://github.com/angular/angular-cli/issues/33728.
20+
//
21+
// Without `disableCodeSplitting`, esbuild hoists a module imported by more than one spec
22+
// entry point into a shared chunk behind a lazy `__esm` initializer, and a class-field
23+
// initializer in another chunk reads the exported value as `undefined` under the jsdom
24+
// runner. All four trigger conditions are required and encoded below:
25+
// 1. two spec entry points import the shared module (so it lands in a shared chunk);
26+
// 2. a component in one entry reads the export during class-field initialization;
27+
// 3. that component's spec file contains an `async` test callback (no `await` needed);
28+
// 4. zone.js is in the polyfills (the `setupApplicationTarget` default), which downlevels
29+
// async and makes esbuild emit the spec entry CommonJS-wrapped.
30+
//
31+
// NOTE: the failure this guards against is sensitive to inert content — adding a top-level
32+
// side effect (even a `console.log`) to the shared or importing module below defused it
33+
// during reduction. Mirror https://github.com/jonmarozick/ng-shared-chunk-repro when
34+
// modifying these fixtures.
35+
it('should provide shared-module exports to class-field initializers in async specs', async () => {
36+
setupApplicationTarget(harness);
37+
38+
harness.useTarget('test', {
39+
...BASE_OPTIONS,
40+
});
41+
42+
// Keep the default project's spec deterministic; a third spec entry that does not touch
43+
// the shared module does not affect the reproduction (verified in a fresh workspace).
44+
await harness.writeFile(
45+
'src/app/app.component.spec.ts',
46+
`
47+
import { describe, it, expect } from 'vitest';
48+
49+
describe('AppComponent placeholder', () => {
50+
it('runs', () => {
51+
expect(1 + 1).toBe(2);
52+
});
53+
});
54+
`,
55+
);
56+
57+
// The shared `const`. Reached from both spec entry points, so it is hoisted into a chunk
58+
// shared between them.
59+
await harness.writeFile(
60+
'src/environments/env-config.ts',
61+
`
62+
export interface DealerConfig {
63+
dealerId: string;
64+
clientKey: string;
65+
}
66+
67+
export const DEALERS: DealerConfig[] = [
68+
{ dealerId: 'dealer-one', clientKey: 'KEY-ONE' },
69+
{ dealerId: 'dealer-two', clientKey: 'KEY-TWO' },
70+
{ dealerId: 'dealer-three', clientKey: 'KEY-THREE' },
71+
{ dealerId: 'dealer-four', clientKey: 'KEY-FOUR' },
72+
];
73+
`,
74+
);
75+
76+
// Reached by both spec entries, so it and env-config.ts land in the shared chunk. Reads the
77+
// const inside a method — after module initialization — and is the passing control.
78+
await harness.writeFile(
79+
'src/app/features/lead-generator/services/lead.service.ts',
80+
`
81+
import { Injectable } from '@angular/core';
82+
83+
import { DEALERS } from '../../../../environments/env-config';
84+
85+
@Injectable({ providedIn: 'root' })
86+
export class LeadService {
87+
resolveClientKey(dealerId: string, clientKey?: string): string {
88+
return clientKey ?? DEALERS.find((d) => d.dealerId === dealerId)?.clientKey ?? '';
89+
}
90+
}
91+
`,
92+
);
93+
94+
await harness.writeFile(
95+
'src/app/features/lead-generator/services/index.ts',
96+
`export * from './lead.service';\n`,
97+
);
98+
99+
// Spec entry point 1 — the second importer that causes the chunk to be shared at all.
100+
await harness.writeFile(
101+
'src/app/features/lead-generator/services/lead.service.spec.ts',
102+
`
103+
import { describe, it, expect } from 'vitest';
104+
import { TestBed } from '@angular/core/testing';
105+
106+
import { LeadService } from './lead.service';
107+
108+
describe('LeadService', () => {
109+
it('reads DEALERS inside a method', () => {
110+
TestBed.configureTestingModule({ providers: [LeadService] });
111+
112+
expect(TestBed.inject(LeadService).resolveClientKey('dealer-one')).toBe('KEY-ONE');
113+
});
114+
});
115+
`,
116+
);
117+
118+
// In the other chunk; reads the shared export eagerly during class-field initialization.
119+
await harness.writeFile(
120+
'src/app/features/lead-generator/lead-generator.container.ts',
121+
`
122+
import { Component, inject } from '@angular/core';
123+
124+
import { LeadService } from './services';
125+
import { DEALERS, DealerConfig } from '../../../environments/env-config';
126+
127+
@Component({
128+
selector: 'app-lead-generator',
129+
standalone: true,
130+
template: '',
131+
})
132+
export class LeadGeneratorContainer {
133+
private readonly leadService = inject(LeadService);
134+
135+
readonly dealers: DealerConfig[] = DEALERS;
136+
readonly dealerOptions = this.dealers.map((d) => d.dealerId);
137+
138+
hasService(): boolean {
139+
return this.leadService != null;
140+
}
141+
}
142+
`,
143+
);
144+
145+
// Spec entry point 2 — the failing case without the fix. The `async` is load-bearing:
146+
// zone.js makes the builder downlevel it, the spec then imports the `__async` helper, and
147+
// esbuild emits this entry CommonJS-wrapped with the component module behind a lazy
148+
// `__esm` initializer. No `await` is needed; a synchronous callback hides the defect.
149+
await harness.writeFile(
150+
'src/app/features/lead-generator/lead-generator.container.spec.ts',
151+
`
152+
import { describe, it, expect } from 'vitest';
153+
import { TestBed } from '@angular/core/testing';
154+
155+
import { LeadGeneratorContainer } from './lead-generator.container';
156+
157+
describe('LeadGeneratorContainer', () => {
158+
it('reads DEALERS in a class-field initialiser', async () => {
159+
const fixture = TestBed.createComponent(LeadGeneratorContainer);
160+
161+
expect(fixture.componentInstance.dealers.length).toBe(4);
162+
});
163+
});
164+
`,
165+
);
166+
167+
const { result } = await harness.executeOnce();
168+
169+
expect(result?.success).toBeTrue();
170+
});
171+
});
172+
});

packages/angular/build/src/tools/esbuild/application-code-bundle.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ export function createBrowserCodeBundleOptions(
7171
supported: getFeatureSupport(zoneless),
7272
};
7373

74+
if (options.disableCodeSplitting) {
75+
// Splitting emits shared chunks that are read across chunk boundaries as live ESM bindings,
76+
// which the unit-test runners' module loading does not reliably preserve.
77+
buildOptions.splitting = false;
78+
}
79+
7480
buildOptions.plugins ??= [];
7581
buildOptions.plugins.push(
7682
createWasmPlugin({ allowAsync: zoneless, cache: loadCache }),

0 commit comments

Comments
 (0)