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
This commit is contained in:
JoostK 2020-10-25 00:19:58 +02:00 committed by Alex Rickabaugh
parent 0ed2c4fef9
commit 3c6edcdf93
2 changed files with 2 additions and 2 deletions

View File

@ -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.)");
};

View File

@ -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