Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: window is not defined #1678

Closed
6 tasks
Gorufi opened this issue May 11, 2020 · 8 comments
Closed
6 tasks

ReferenceError: window is not defined #1678

Gorufi opened this issue May 11, 2020 · 8 comments

Comments

@Gorufi
Copy link

Gorufi commented May 11, 2020

馃悶 Bug report

What modules are related to this issue?

  • aspnetcore-engine
  • builders
  • common
  • express-engine
  • hapi-engine
  • module-map-ngfactory-loader

Is this a regression?

No

Description

I was trying to add Angular Universal to our project but, when I use npm run dev:ssr I get the error metioned on the title, here's the entire message:

ReferenceError: window is not defined
    at Object.<anonymous> (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:209202:30237)
    at C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:209163:37
    at Object../node_modules/jspdf/dist/jspdf.min.js (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:209165:112)
    at __webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)
    at Object../src/app/components/search/search.component.ts (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:255011:15)
    at __
webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)
    at Object../src/app/app-routing.module.ts (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:253310:28)
    at __webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)
    at Object../src/app/app.module.ts (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:253393:30)
    at __webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)

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

I tried adding the following code to server.ts, as suggested in another thread of this exact problem, however, this did not work:

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;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
global['localStorage'] = localStorage;

After this, I really don't know what to do now, so I come here for help.

Since this is my first time posting here, please tell me if you need something else added.

馃敩 Minimal Reproduction

Running npm run server:ssr prompts the error.

馃實 Your Environment


Angular CLI: 9.0.7
Node: 12.16.0
OS: win32 x64

Angular: 9.0.7
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.900.7
@angular-devkit/build-angular     0.900.7
@angular-devkit/build-optimizer   0.900.7
@angular-devkit/build-webpack     0.900.7
@angular-devkit/core              9.0.7
@angular-devkit/schematics        9.0.7
@angular/cdk                      9.2.0
@angular/flex-layout              9.0.0-beta.29
@angular/localize                 9.1.1
@angular/material                 9.2.0
@ngtools/webpack                  9.0.7
@nguniversal/builders             9.1.1
@nguniversal/common               9.0.2
@nguniversal/express-engine       9.0.2
@schematics/angular               9.0.7
@schematics/update                0.900.7
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2
@jasonburrows
Copy link

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

It may not solve your problem though as domino doesn't implement everything you might need.

@steppe87
Copy link

@jasonburrows your hint worked for me! Thanks!

@CaerusKaru
Copy link
Member

Thank you @jasonburrows, closing.

@aneudysamparo
Copy link

Can anyone post the solution?

@isawk
Copy link

isawk commented Jul 19, 2020

I think I have tried all the implementations on the internet to resolve window not defined issues ssr and third party libraries in this instance keycloak-js and unfortunately nothing seems to work using of domino regardless where I place implementations before import { AppServerModule } from './src/main.server'; after it, an below i have all within export function app(): express.Express and nothing works.

Project needs keycloak and ssr it is an omni channel solution which must implement SSO and enable SEO. Details below.

environment

Angular CLI: 10.0.3
Node: 12.18.2
OS: darwin x64

Angular: 10.0.4
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, platform-server
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.1000.3
@angular-devkit/build-angular     0.1000.3
@angular-devkit/build-optimizer   0.1000.3
@angular-devkit/build-webpack     0.1000.3
@angular-devkit/core              10.0.2
@angular-devkit/schematics        10.0.3
@angular/cli                      10.0.3
@ngtools/webpack                  10.0.3
@nguniversal/builders             10.0.1
@nguniversal/common               10.0.1
@nguniversal/express-engine       10.0.1
@schematics/angular               10.0.3
@schematics/update                0.1000.3
rxjs                              6.5.5
typescript                        3.9.7
webpack                           4.43.0
//SSR Dom errors polyfile and work around
const domino = require('domino');
import "localstorage-polyfill";

//angular/express
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { existsSync, readFileSync } from 'fs';

const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index.html';

//SSR Dom errors polyfile and work around
const template = readFileSync(join(distFolder, indexHtml)).toString();
const window = domino.createWindow(template);

(global as any).window = window;
(global as any).document = window.document;
(global as any).Event = window.Event;
(global as any).KeyboardEvent = window.KeyboardEvent;
(global as any).MouseEvent = window.MouseEvent;
(global as any).FocusEvent = window.FocusEvent;
(global as any).PointerEvent = window.PointerEvent;
(global as any).HTMLElement = window.HTMLElement;
(global as any).HTMLElement.prototype.getBoundingClientRect = () => {
  return {
    left: '',
    right: '',
    top: '',
    bottom: ''
  };
};
// xmlhttprequest
// (global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
(global as any).navigator = window.navigator;
(global as any).localStorage = window.localStorage;
(global as any).DOMTokenList = window.DOMTokenList;
Object.defineProperty(window.document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});
(global as any).CSS = null;
(global as any).Prism = null;
//SSR Dom errors polyfile and work around


import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';


// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {

  const server = express();

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run(): void {
  const port = process.env.PORT || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

error

Compiled successfully. /server/main.js:129404
})(window, function (sha256_imported, base64js_imported) {
   ^

ReferenceError: window is not defined
    at Object../node_modules/keycloak-js/dist/keycloak.js 

@milankrushna
Copy link

Try with keycloak-angular insted of keycloak-js npm package. It may be solve your problem.

@isawk
Copy link

isawk commented Jul 19, 2020

Try with keycloak-angular insted of keycloak-js npm package. It may be solve your problem.

I am using keycloak-angular issue reported with no luck on fix, apparently some claim work arounds above work with angular 8,9 issues/263

    "keycloak-angular": "^7.3.1",
    "keycloak-js": "^10.0.2",

@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Aug 19, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants