diff --git a/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions.ts b/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions.ts index 08947506049f..75cbdd86ecdf 100644 --- a/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions.ts +++ b/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions.ts @@ -71,6 +71,13 @@ export default function (): PluginObject { return; } + // Do not annotate standalone expression statements. + // Standalone expression statements are executed solely for their side effects; + // marking them pure causes minifiers to drop them as dead code. + if (path.parentPath.isExpressionStatement()) { + return; + } + const callee = path.get('callee'); if ( (callee.isFunctionExpression() || callee.isArrowFunctionExpression()) && @@ -96,6 +103,13 @@ export default function (): PluginObject { return; } + // Do not annotate standalone expression statements. + // Standalone expression statements are executed solely for their side effects; + // marking them pure causes minifiers to drop them as dead code. + if (path.parentPath.isExpressionStatement()) { + return; + } + const { topLevelSafeMode = false } = state.opts; if (!topLevelSafeMode) { diff --git a/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions_spec.ts b/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions_spec.ts index c9d7eafd4aee..f3df13b1cca9 100644 --- a/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions_spec.ts +++ b/packages/angular_devkit/build_angular/src/tools/babel/plugins/pure-toplevel-functions_spec.ts @@ -154,6 +154,28 @@ describe('pure-toplevel-functions Babel plugin', () => { `), ); + it('does not annotate top-level call expression statements', testCaseNoChange('someCall();')); + + it( + 'does not annotate top-level IIFE expression statements', + testCaseNoChange(` + (() => { + _defineProperty(_Injector, 'ɵprov', ɵɵdefineInjectable({ token: _Injector })); + _defineProperty(_Injector, '__NG_ELEMENT_ID__', -1); + })(); + `), + ); + + it( + 'does not annotate top-level static block helper calls', + testCaseNoChange(` + _staticBlock(); + _staticBlock2(); + `), + ); + + it('does not annotate top-level new expression statements', testCaseNoChange('new SomeClass();')); + describe('topLevelSafeMode: true', () => { it( 'annotates top-level `new InjectionToken` expressions',