Home > Software design >  ReferenceError: window is not defined (Angular Universal)
ReferenceError: window is not defined (Angular Universal)

Time:07-28

ReferenceError: window is not defined at Object.79604 (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:26154:360416) at webpack_require (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:254150:42) at Module.20054 (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:246050:68) at webpack_require (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:254150:42) at Object.83747 (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:7138:12) at webpack_require (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:254150:42) at Object.72402 (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:19325:13) at webpack_require (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:254150:42) at Object.90158 (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:659:29) at webpack_require (C:\Users\aakas\Desktop\universal\dist\project\server\main.js:254150:42)

A server error has occurred. node exited with 1 code. connect ECONNREFUSED 127.0.0.1:49936

CodePudding user response:

Not sure if this is the answer you are looking for but when working with NextJS you also get that kind of error and the answer is wrapping the document or window inside this:

if (typeof window !== 'undefined') {
  # write your code here
}

So if you have, for example, document.querySelector() around your app you only need to wrap it like this:

if (typeof window !== 'undefined') {
  document.querySelector()
}

Hope it helps!

CodePudding user response:

try To use that workaround it has to appear before import { AppServerModule } from './src/main.server'; maybe work with you

CodePudding user response:

if you use third party library and this error accurs because of that you have two options:

1- add this to your server.ts:

const MockBrowser = require('mock- browser').mocks.MockBrowser;
const mock = new MockBrowser();

global.document = mock.getDocument();
global.window = mock.getWindow();

2- use that library only in browser:

in your ts file:

isBrowser = false;
constructor(@Inject(PLATFORM_ID) private platformId){
isBrowser  = isPlatformBrowser(this.platformId);
}

in your html file:

<thirdparty *ngIf="isBrowser"></thirdparty>

if you use window in your typescript:

if (this.isBrowser) {
window.....
}
  • Related