Skip to content

Commit bc6b631

Browse files
committed
fix(@angular-devkit/build-angular): mark InjectionToken as pure for improved tree-shaking
`new InjectionToken(...)` is not considered pure by default by build tools, which prevents it from being tree-shaken when unused. This can lead to unused services being included in production bundles if they are provided as a default value for a token. This change marks `new InjectionToken(...)` calls as pure. The `InjectionToken` constructor is side-effect free; its only purpose is to create a token for the dependency injection system. Marking it as pure is safe and allows build tools like esbuild to tree-shake unused tokens and their dependencies. Closes #31270 (cherry picked from commit acd785a)
1 parent e510ff8 commit bc6b631

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

packages/angular_devkit/build_angular/src/tools/babel/presets/application.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export interface ApplicationPresetOptions {
5757
inputSourceMap: unknown;
5858
};
5959
optimize?: {
60-
pureTopLevel: boolean;
60+
topLevelSafeMode: boolean;
6161
wrapDecorators: boolean;
6262
};
6363

@@ -220,14 +220,12 @@ export default function (api: unknown, options: ApplicationPresetOptions) {
220220
elideAngularMetadata,
221221
markTopLevelPure,
222222
} = require('@angular/build/private');
223-
if (options.optimize.pureTopLevel) {
224-
plugins.push(markTopLevelPure);
225-
}
226-
227-
plugins.push(elideAngularMetadata, adjustTypeScriptEnums, [
228-
adjustStaticMembers,
229-
{ wrapDecorators: options.optimize.wrapDecorators },
230-
]);
223+
plugins.push(
224+
[markTopLevelPure, { topLevelSafeMode: options.optimize.topLevelSafeMode }],
225+
elideAngularMetadata,
226+
adjustTypeScriptEnums,
227+
[adjustStaticMembers, { wrapDecorators: options.optimize.wrapDecorators }],
228+
);
231229
}
232230

233231
if (options.instrumentCode) {

packages/angular_devkit/build_angular/src/tools/babel/webpack-loader.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ export default custom<ApplicationPresetOptions>(() => {
138138
customOptions.optimize = {
139139
// Angular packages provide additional tested side effects guarantees and can use
140140
// otherwise unsafe optimizations. (@angular/platform-server/init) however has side-effects.
141-
pureTopLevel: AngularPackage && sideEffectFree,
141+
topLevelSafeMode: !(AngularPackage && sideEffectFree),
142142
// JavaScript modules that are marked as side effect free are considered to have
143143
// no decorators that contain non-local effects.
144144
wrapDecorators: sideEffectFree,

0 commit comments

Comments
 (0)