From 3c6edcdf9340bfb81323ec576f9d05bbedd4735e Mon Sep 17 00:00:00 2001 From: JoostK Date: Sun, 25 Oct 2020 00:19:58 +0200 Subject: [PATCH] fix(core): do not error when `ngDevMode` is undeclared (#39415) In production mode, the `ngDevMode` global may not have been declared. This is typically not a problem, as optimizers should have removed all usages of the `ngDevMode` variables. This does however require the bundler/optimizer to have been configured in a certain way, as to allow for `ngDevMode` guarded code to be removed. As an example, Terser can be configured to remove the `ngDevMode` guarded code using the following configuration: ```js const terserOptions = { // ... compress: { // ... global_defs: require('@angular/compiler-cli').GLOBAL_DEFS_FOR_TERSER, } } ``` (Taken from https://github.com/angular/angular/issues/31595#issuecomment-519129090) If this is not done, however, the bundle should still work (albeit with larger code size due to missed tree-shaking opportunities). This commit adds a check for whether `ngDevMode` has been declared, as it is a top-level statement that executes before `ngDevMode` has been initialized. Fixes #31595 PR Close #39415 --- integration/side-effects/snapshots/core/esm2015.js | 2 +- packages/core/src/core.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integration/side-effects/snapshots/core/esm2015.js b/integration/side-effects/snapshots/core/esm2015.js index d12748503d..13a1af3941 100644 --- a/integration/side-effects/snapshots/core/esm2015.js +++ b/integration/side-effects/snapshots/core/esm2015.js @@ -12,6 +12,6 @@ const __global = "undefined" !== typeof global && global; const _global = __globalThis || __global || __window || __self; -if (ngDevMode) _global.$localize = _global.$localize || function() { +if ("undefined" !== typeof ngDevMode && ngDevMode) _global.$localize = _global.$localize || function() { throw new Error("It looks like your application or one of its dependencies is using i18n.\n" + "Angular 9 introduced a global `$localize()` function that needs to be loaded.\n" + "Please run `ng add @angular/localize` from the Angular CLI.\n" + "(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.\n" + "For server-side rendering applications add the import to your `main.server.ts` file.)"); }; diff --git a/packages/core/src/core.ts b/packages/core/src/core.ts index 019394da77..b59aabbbe1 100644 --- a/packages/core/src/core.ts +++ b/packages/core/src/core.ts @@ -38,7 +38,7 @@ export {Sanitizer} from './sanitization/sanitizer'; export * from './codegen_private_exports'; import {global} from './util/global'; -if (ngDevMode) { +if (typeof ngDevMode !== 'undefined' && ngDevMode) { // This helper is to give a reasonable error message to people upgrading to v9 that have not yet // installed `@angular/localize` in their app. // tslint:disable-next-line: no-toplevel-property-access