Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 SSR - where to set global['window'] (using domino)?

After upgrading to Angular 9, I'm getting error ReferenceError: window is not defined when running yarn serve:ssr.

In our Angular apps, we use trick with Domino to emulate window for SSR (as in https://github.com/Angular-RU/angular-universal-starter/blob/master/server.ts#L21 ).

So after ng update I have added these lines after imports in server.ts:


const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

// Emulate browser APIs
const domino = require('domino');
const fs = require('fs');
const templateA = fs.readFileSync(join(distFolder, indexHtml)).toString();

const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;
global['window'] = win;
global['document'] = win.document;

However, it seems that setting global['window'] is happening either too late or never.

Do you have any idea where to set global['window'] so the angular components and libraries can access it in SSR?

like image 976
Lukáš Březina Avatar asked Feb 10 '20 11:02

Lukáš Březina


1 Answers

Solved, thanks to this comment https://github.com/angular/universal/issues/1678#issuecomment-627031128

The key is to have line

import { AppServerModule } from './src/main.server';

after the definition of global['window']

Beware the autoformatters in your editor, which usually put the import lines on top of the file automatically :)

like image 139
Lukáš Březina Avatar answered Oct 26 '22 18:10

Lukáš Březina