yeet
yeet

Reputation: 33

Angular 15 universal ReferenceError: window is not defined

I have a big angular project that i want to convert to SSR. i know there are a ton of questions about this, all are answered with the same fix of using "isPlatformBrowser(this.platformId);". I am not using 'window' anywhere in my code, so it must be coming from a library somewhere. Not every library has an alternative, so i'm stuck with these libraries. Isn't there another way than going through every component in my project and to add checks everywhere with "isPlatformBrowser"?

Upvotes: 0

Views: 867

Answers (1)

joccafi
joccafi

Reputation: 88

Unfortunately you have try some solutions in the web, but I think there is no easy solution to solve your specific case.

You can try to modify your angular.json:

"server": {
  "builder": "@angular-devkit/build-angular:server",
   "options": {
     "outputPath": "dist/PROJECT_NAME/server",
     "main": "server.ts",
     "tsConfig": "tsconfig.server.json",
     "stylePreprocessorOptions": {
       "includePaths": ["src/assets/styles"]
      },
     "externalDependencies": ["@firebase/firestore"]
   }
}

The externalDependencies option allows you to exclude the listed dependencies in the array from the main bundle and instead, the generated bundle relies on these dependencies to be available during runtime.

You should create a service that wraps the global Window object.

import { Injectable } from '@angular/core';

function _window(): any {
  return window;
}

@Injectable()
export class WindowRef {
 get nativeWindow(): any {
   return _window();
 }
}

The text and code above were taken from this article. Please, take a look in the author's (Thabo Ambrose) solution.

Attention: Until today there is an open issue regarding isPlatformBrowser on Github.

Upvotes: 1

Related Questions