简体   繁体   中英

How to fix "ReferenceError: window is not defined" error in angular 6 universal server.js

I execute the following command on angular cli command line tool, to install universal package for angular6 'ng add @ng-toolkit/universal'. It installed good,after that i execute npm run build:prod and it also runs very well. Now finally I run 'npm run server'.But this throws me error without giving me launching url.

here it is throwing error in server.js file, how to fix it.

ReferenceError: window is not defined
    at Object.exports.__esModule (D:\ANGULAR2\dist\server.js:122614:14)
    at __webpack_require__ (D:\ANGULAR2\dist\server.js:122314:31)
    at Object.exports.__esModule (D:\ANGULAR2\dist\server.js:122359:19)
    at __webpack_require__ (D:\ANGULAR2\dist\server.js:122314:31)
    at Object.exports.__esModule (D:\ANGULAR2\dist\server.js:122343:21)
    at __webpack_require__ (D:\ANGULAR2\dist\server.js:122314:31)
    at D:\ANGULAR2\dist\server.js:122334:19
    at D:\ANGULAR2\dist\server.js:122337:11
    at webpackUniversalModuleDefinition (D:\ANGULAR2\dist\server.js:122292:21)
    at Object.exports.__esModule (D:\ANGULAR2\dist\server.js:122294:4)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! rssmtechwood@0.0.0 serverrl `node local.js`
npm ERR! Exit status 1

as a workaround i replace window with global.

var work = global.document.createElement('div'); but window,document element is being used in many places of server.js

function(module, exports)

{   

        'use strict';   

        exports.__esModule = true;

        var tagSoup = false;

        var selfClose = false;  

        var work = window.document.createElement('div');

}


function isBrowser() 

{

    return (typeof window !== 'undefined' && typeof window.document !== 'undefined');

}

I expect window.document,window to be replaced by nodejs syntax for the above sample code.

When running your app on Angular Universal, the document , window and navigator objects will always be undefined and have no equivalent.

The reason is simple, when running an Angular app on client side, an (almost) empty HTML file is served, then the JavaScript takes over, and modifies the DOM by using window , document , etc.

When running an Angular app on server side, the execution context is totally different, Node.js has no knowledge of any browser, it just generates HTML as a full plain string without interpreting it at all. That's why those keywords can't be used in this context.

So whatever you are trying to achieve with those keywords, you'll have to find a different way for server-side rendering, or just conditionally disable this code, so it only executes on client side, and doesn't throw errors on server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM