From fb9ea53dbe740c5bb32f5a663ce484487b5faea7 Mon Sep 17 00:00:00 2001 From: Paul Gschwendtner Date: Fri, 8 Dec 2017 18:55:40 +0100 Subject: [PATCH] fix: safety check for window in common module. (#8816) * Currently if someone renders his Angular application using server side rendering, the `MatCommonModule` will throw an error due to missing `window` variable checks. Fixes #8809 --- src/lib/core/common-behaviors/common-module.ts | 11 +++++++++-- src/universal-app/prerender.ts | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/lib/core/common-behaviors/common-module.ts b/src/lib/core/common-behaviors/common-module.ts index 48a77e4da9d..9108f1c8659 100644 --- a/src/lib/core/common-behaviors/common-module.ts +++ b/src/lib/core/common-behaviors/common-module.ts @@ -37,6 +37,9 @@ export class MatCommonModule { /** Reference to the global `document` object. */ private _document = typeof document === 'object' && document ? document : null; + /** Reference to the global 'window' object. */ + private _window = typeof window === 'object' && window ? window : null; + constructor(@Optional() @Inject(MATERIAL_SANITY_CHECKS) private _sanityChecksEnabled: boolean) { if (this._areChecksEnabled() && !this._hasDoneGlobalChecks) { this._checkDoctypeIsDefined(); @@ -52,7 +55,7 @@ export class MatCommonModule { /** Whether the code is running in tests. */ private _isTestEnv() { - return window['__karma__'] || window['jasmine']; + return this._window && (this._window['__karma__'] || this._window['jasmine']); } private _checkDoctypeIsDefined(): void { @@ -90,7 +93,11 @@ export class MatCommonModule { /** Checks whether HammerJS is available. */ _checkHammerIsAvailable(): void { - if (this._areChecksEnabled() && !this._hasCheckedHammer && !window['Hammer']) { + if (this._hasCheckedHammer || !this._window) { + return; + } + + if (this._areChecksEnabled() && !this._window['Hammer']) { console.warn( 'Could not find HammerJS. Certain Angular Material components may not work correctly.'); } diff --git a/src/universal-app/prerender.ts b/src/universal-app/prerender.ts index a19a93377be..df558311377 100644 --- a/src/universal-app/prerender.ts +++ b/src/universal-app/prerender.ts @@ -1,4 +1,3 @@ -import {enableProdMode} from '@angular/core'; import {renderModuleFactory} from '@angular/platform-server'; import {readFileSync, writeFileSync} from 'fs-extra'; import {log} from 'gulp-util'; @@ -7,7 +6,8 @@ import 'reflect-metadata'; import 'zone.js'; import {KitchenSinkServerModuleNgFactory} from './kitchen-sink/kitchen-sink.ngfactory'; -enableProdMode(); +// Do not enable production mode, because otherwise the `MatCommonModule` won't execute +// the browser related checks that could cause NodeJS issues. const result = renderModuleFactory(KitchenSinkServerModuleNgFactory, { document: readFileSync(join(__dirname, 'index.html'), 'utf-8')