5

Error :

factory(require("jquery"), document, window, navigator);
                               ^ReferenceError: document is not defined

Facing issue angular universal rendering server side, I have googled this and go through many posts but didn't get any helpful resource.

Dileep Pal
  • 81
  • 1
  • 1
  • 5

4 Answers4

5

Jquery works on the browser side and browser functions is not supported on server side. for example if you want to use jquery in angular universal you will have to make sure you are using it on browser side only.

For example you can do the following.

In your component.ts file import the following.

import { isPlatformServer } from '@angular/common';
import * as $ from 'jquery';

and then in your ngOnInit function do the following

constructor(@Inject(PLATFORM_ID) private platformId: any) {}
  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
     /* jQuery here */
     $("#test-button").click(function () {
       alert('WOOOW');
       $(this).css("background","#000");
    });
  }
}
faizan baig
  • 1,283
  • 15
  • 21
2

I was having same issue, searched. Found this answer on https://github.com/angular/universal-starter/issues/623

Put this code in your server.ts file

const domino = require("domino");
const fs = require("fs");
const path = require("path");
const templateA = fs
  .readFileSync(path.join("dist/browser", "index.html"))
  .toString();
const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;

global["window"] = win;
global["document"] = win.document;
global["branch"] = null;
global["object"] = win.object;
Mann
  • 89
  • 1
  • 7
1

To avoid your errors you can create mock for document and window objects in NodeJS server implementation server.ts:

// ssr DOM
const domino = require('domino');
const fs = require('fs');
const path = require('path');
// index from browser build!
const template = fs.readFileSync(path.join(DIST_FOLDER, 'index.html')).toString();
// for mock global window by domino
const win = domino.createWindow(template);
// mock
global['window'] = win;
// not implemented property and functions
Object.defineProperty(win.document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});

// mock documnet
global['document'] = win.document;
// othres mock
global['CSS'] = null;
// global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;
global['Prism'] = null;

Here you can find working example

After modifications rebuild your server sources again.

Krzysztof Raciniewski
  • 4,735
  • 3
  • 21
  • 42
0

If you are using server-side than you must have to add check whether the platform is browser or server because keywords like Document, Window are not available in Server side support

you can use isPlatformBrowser from angular.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215