How do I run Chart.js with Angular 10 SSR / universal?

863 Views Asked by At

I'm trying to let run Chart.js (ng2-charts) on Angular 10 with server-side-rendered pages. Unfortunately, it always crashes with:

ERROR { Error: Uncaught (in promise): ReferenceError: window is not defined

ReferenceError: window is not defined

So my question is if anybody was able to get it to run?

1

There are 1 best solutions below

0
On BEST ANSWER

The reason why this is happening is because you are running SSR with NodeJS and there is no window object, so you need a NodeJS replacement.

I suggest installing domino

npm i --save-dev domino

Then in your server.ts

const domino = require('domino');

const template = fs
  .readFileSync(path.join('dist/browser', 'index.html')) // Or whereever your rendered index.html is
  .toString();


const window = domino.createWindow(template);
(global as any).window = window;
(global as any).document = window.document;