“ERROR in window is not defined” webpack general e

2020-02-12 22:05发布

问题:


I'm trying to deploy my first angular app but during the execution of deploy, in the middle of the command:

node node_modules/webpack/bin/webpack.js --mode=production --env.prod

(A.K.A. webpack --mode=production --config webpack.config.js --env.prod)

I get a generic error which does not provide me more informations than the following:

Hash: 7b126cdcbdda85d6b0f304152e501136ec85ed58
Version: webpack 4.6.0
Child
    Hash: 7b126cdcbdda85d6b0f3
    Time: 13298ms
    Built at: 2018-04-23 12:27:51
     1 asset
    Entrypoint main-client = main-client.js

    ERROR in window is not defined
Child
    Hash: 04152e501136ec85ed58
    Time: 13281ms
    Built at: 2018-04-23 12:27:51
     1 asset
    Entrypoint main-server = main-server.js

    ERROR in window is not defined

Main-server and Main-client are both webpack-generated files and the only usage of "window" in my code is to execute the window.history.back() command but even commenting it, the error still comes up.

Does anyone knows how to solve it?

My webpack version is 4.6.0 and my webpack.config.js content is the following:
||
===> UPDATE - unnecessary webpack.config.js content as not related to the issue itself

回答1:

This is probably cause because you're referring to window directly somewhere in your code. THIS IS NOT BEST PRACTISE!! Sometimes, (Server side) the window object is not defined and cause this problems. Same if a third-part library uses that.

So check your code first, find where you're using window directly and wrap inside a PLATFORMID like this example:

 import { PLATFORM_ID } from '@angular/core';
 import { isPlatformBrowser, isPlatformServer } from '@angular/common';
 
 constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... }
 
 ngOnInit() {
   if (isPlatformBrowser(this.platformId)) {
      // Client only code.
      ...
   }
   if (isPlatformServer(this.platformId)) {
     // Server only code.
     ...
   }
 }

Or, if you can't find it, probably a library is still using it. Check this issue on github, it will explain you better than me the problem:

https://github.com/webpack/react-starter/issues/37

Hope this will help you =)

PS: same problem when i had to implement a Server Side Rendering.. I was using window EVERYWHERE in code. From that moment, when i have to use it, i always find another way to do the same thing.

You could also try putting target: "web" inside your webpack.config.js


EDIT FROM THE ONE WHO ASKED THE QUESTION

See also this issue on github, it provides the solution for this issue: https://github.com/webpack/webpack/issues/7112