Angular 9 and SSR - window is not defined

Viewed 1084

I am using Angular 9 and SSR and I am getting the error on one of the packages.

const DragEvevent = window.DragEvent

ReferenceError: window is not defined

On the ngx-chips package

We already tried adding to the nodeJs the variables:

const domino = require('domino');
const fs = require('fs');
const template = fs.readFileSync(join(join(process.cwd(), 'dist/emaua-front/browser'), 'index.html')).toString();
console.log(template);
const win = domino.createWindow(template);

// mock
global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;

But still the error persists.

Update

After updating all packages I got the error: 
ERROR in multi ./src/assets/css/ripple.min.scss ./src/assets/css/lounge.scss ./src/assets/css/discovery.scss ./src/assets/css/main.scss ./src/styles.scss ./node_modules/roboto-fontface/css/roboto/roboto-fontface.css ./node_modules/material-design-icons/iconfont/material-icons.css ./node_modules/bootstrap/dist/css/bootstrap.min.css ./node_modules/bootstrap/dist/css/bootstrap-theme.min.css ./node_modules/ng-bootstrap-to-bootstrap-3/dist/ng-bootstrap-to-bootstrap-3.min.css ./node_modules/jquery-ui-dist/jquery-ui.min.css ./node_modules/jquery-ui-dist/jquery-ui.theme.min.css ./node_modules/ag-grid-community/dist/styles/ag-grid.css ./node_modules/ag-grid-community/dist/styles/ag-theme-balham.css ./node_modules/slick-carousel/slick/slick.scss ./node_modules/slick-carousel/slick/slick-theme.scss ./src/assets/css/animate.css ./node_modules/cookieconsent/build/cookieconsent.min.css
Module not found: Error: Can't resolve '/Users/vinh/learning/front-end/node_modules/bootstrap/dist/css/bootstrap-theme.min.css' in '/Users/vinh/learning/front-end'
this.debug is not a function

After that I applied the fix as said in here

And again I am getting the same error like:

const DragEvent = window.DragEvent;
                  ^

ReferenceError: window is not defined

On the ngx-chips package

UPDATE

The problems we have in ngx-chips is something that was happening before.

https://github.com/Gbuomprisco/ngx-chips/issues/740 https://github.com/Gbuomprisco/ngx-chips/issues/786

Does anyone knows a way of overcoming this problem?

1 Answers

I upgraded to Angular 10 and I had the same problem with ngx-chips on the server.

I solved this problem as follows: I, probably like many, do not really need this component when rendering on the server. Too lazy to create a separate project to exclude this module. So I just disabled this component.

In template:

<div *ngIf="isBrowser()">
   <tag-input [(ngModel)]=...  
   </tag-input>
</div>

In typescript:

isBrowser() {
  if (window) {
       return true;
  }
  return false;
}
Related