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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webpack 4.0.1 | WebWorker window is not defined #6642

Closed
renarsvilnis opened this issue Mar 1, 2018 · 20 comments
Closed

Webpack 4.0.1 | WebWorker window is not defined #6642

renarsvilnis opened this issue Mar 1, 2018 · 20 comments

Comments

@renarsvilnis
Copy link

renarsvilnis commented Mar 1, 2018

Do you want to request a feature or report a bug?

Bug 🐛

What is the current behavior?

When requiring web-worker (using worker-loader) recieve error Uncaught ReferenceError: window is not defined.

First ~50 lines of built worker file
/******/ (function(modules) { // webpackBootstrap
/******/ 	var parentHotUpdateCallback = window["webpackHotUpdate"];
/******/ 	window["webpackHotUpdate"] = // eslint-disable-next-line no-unused-vars
/******/ 	function webpackHotUpdateCallback(chunkId, moreModules) {
/******/ 		hotAddUpdateChunk(chunkId, moreModules);
/******/ 		if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
/******/ 	} ;
/******/
/******/ 	// eslint-disable-next-line no-unused-vars
/******/ 	function hotDownloadUpdateChunk(chunkId) {
/******/ 		importScripts(__webpack_require__.p + "" + chunkId + "." + hotCurrentHash + ".hot-update.js");
/******/ 	}
/******/
/******/ 	// eslint-disable-next-line no-unused-vars
/******/ 	function hotDownloadManifest(requestTimeout) {
/******/ 		requestTimeout = requestTimeout || 10000;
/******/ 		return new Promise(function(resolve, reject) {
/******/ 			if (typeof XMLHttpRequest === "undefined")
/******/ 				return reject(new Error("No browser support"));
/******/ 			try {
/******/ 				var request = new XMLHttpRequest();
/******/ 				var requestPath = __webpack_require__.p + "" + hotCurrentHash + ".hot-update.json";
/******/ 				request.open("GET", requestPath, true);
/******/ 				request.timeout = requestTimeout;
/******/ 				request.send(null);
/******/ 			} catch (err) {
/******/ 				return reject(err);
/******/ 			}
/******/ 			request.onreadystatechange = function() {
/******/ 				if (request.readyState !== 4) return;
/******/ 				if (request.status === 0) {
/******/ 					// timeout
/******/ 					reject(
/******/ 						new Error("Manifest request to " + requestPath + " timed out.")
/******/ 					);
/******/ 				} else if (request.status === 404) {
/******/ 					// no update available
/******/ 					resolve();
/******/ 				} else if (request.status !== 200 && request.status !== 304) {
/******/ 					// other failure
/******/ 					reject(new Error("Manifest request to " + requestPath + " failed."));
/******/ 				} else {
/******/ 					// success
/******/ 					try {
/******/ 						var update = JSON.parse(request.responseText);
/******/ 					} catch (e) {
/******/ 						reject(e);
/******/ 						return;
/******/ 					}
/******/ 					resolve(update);
/******/ 				}
/******/ 			};
/******/ 		});
/******/ 	}

// More code... (think it's irrelevant)

screen shot 2018-03-01 at 23 12 59

What is the expected behavior?

To inject right template for web-workers that won't include/use window element.

Please mention other relevant information such as the browser version, Node.js version, webpack version, and Operating System.

I'm using electron-render as webpack build target. Tried changing it to web and inspecting the worker file, but still didn't work!

  • Webpack config (filtered):

     {
       mode: 'development',
       devtool: 'eval-source-map',
       target: 'electron-renderer',
       entry: [
         'react-hot-loader/patch',
         path.join(__dirname, 'src/index.js'),
         'webpack-hot-middleware/client?reload=true&path=http://localhost:3000__webpack_hmr&overlay=false'
       ],
       output: {
         path: path.join(__dirname, 'dist'),
         filename: 'bundle.js'
         publicPath: 'http://localhost:3000'
       },
       module: {
         rules: [
           {
             enforce: 'pre',
             test: /\.js$/i,
             exclude: /node_modules/,
             use: {
               loader: 'eslint-loader',
               options: {
                 fix: true,
                 failOnWarning: false,
                 failOnError: false
               }
             }
           },
           {
             test: /\.worker.js$/i,
             exclude: /node_modules/,
             use: [
               'worker-loader'
             ]
           },
           {
             test: /\.js$/i,
             exclude: /node_modules/,
             use: [
               'babel-loader'
             ]
           },
           // ...
         ]
       },
       resolve: {
         modules: [
           path.resolve('./src'),
           'node_modules'
         ]
       },
       plugins: [
     	new webpack.HotModuleReplacementPlugin(),
     	new webpack.NamedModulesPlugin(),
     	new webpack.DefinePlugin({
       	  'process.env.NODE_ENV': JSON.stringify('development')
     	})
       ]
     }
  • NPM Packages (filtered):

     "electron": "2.0.0-beta.1"
     "react-hot-loader": "4.0.0"
     "webpack": "4.0.1"
     "webpack-cli": "2.0.9"
     "webpack-dev-middleware": "3.0.0"
     "webpack-hot-middleware": "2.21.1"
     "webpack-merge": "4.1.2"
     "worker-loader": "1.1.1"
    
  • Operating System: OSX 10.12.6

  • Node.js: v9.5.0

@rettgerst
Copy link

disabling hot module replacement fixed this for me.

@renarsvilnis
Copy link
Author

renarsvilnis commented Mar 1, 2018

@rettgerst Disabling new webpack.HotModuleReplacementPlugin() helped as a temporary fix.

@nowy
Copy link

nowy commented Mar 3, 2018

Is there an ETA on this?

@sokra
Copy link
Member

sokra commented Mar 4, 2018

#6525 will fix this.

As workaround with HMR: output.globalObject: "this"

@sokra
Copy link
Member

sokra commented Mar 4, 2018

Closing in favor of #6525

@sokra sokra closed this as completed Mar 4, 2018
@e00dan
Copy link

e00dan commented Mar 5, 2018

@sokra Where should one add this output.globalObject?

@just-jeb
Copy link

just-jeb commented Mar 7, 2018

@kuzirashi inside the output section of webpack config. Like this:

output: {
       path: path.join(__dirname, 'dist'),
       filename: 'bundle.js'
       publicPath: 'http://localhost:3000',
       globalObject: 'this'
},

@odama626
Copy link

I ran into this as well, while doing some research I think I may have found a fix, previously implemented in webpack-dev-server. I believe this issue is relevant.

https://github.com/webpack/webpack-dev-server/issues/628

if so, simply changing window to self should fix the issue

dtinth added a commit to bemusic/bemuse that referenced this issue Apr 3, 2018
disarticulate added a commit to disarticulate/quasar-framework.org that referenced this issue May 20, 2018
See webpack/webpack#6642 for web workers issues
@masx200
Copy link

masx200 commented Jun 24, 2019

终于找到解决办法了!

@masx200
Copy link

masx200 commented Jun 29, 2019

olragon added a commit to olragon/binpackingjs that referenced this issue Sep 10, 2019
DeepDiver1975 added a commit to owncloud/owncloud-sdk that referenced this issue Oct 14, 2019
whacked added a commit to whacked/cache-control-parser that referenced this issue Jun 27, 2020
The current build uses webpack 4, which outputs an undefined
`window` reference and causes

```
ReferenceError: window is not defined
```

upon import via e.g. `require("cache-control-parser")` from
node. Updating the webpack config fixes the error after rebuild.
References:

- https://stackoverflow.com/a/58718315
- webpack/webpack#6642
- https://webpack.js.org/configuration/output/#outputglobalobject
whacked added a commit to whacked/cache-control-parser that referenced this issue Jun 27, 2020
The current build uses webpack 4, which outputs an undefined
`window` reference and causes

```
ReferenceError: window is not defined
```

upon import via e.g. `require("cache-control-parser")` from
node. Updating the webpack config fixes the error after rebuild.
References:

- https://stackoverflow.com/a/58718315
- webpack/webpack#6642
- https://webpack.js.org/configuration/output/#outputglobalobject
whacked added a commit to whacked/cache-control-parser that referenced this issue Jun 27, 2020
The current build uses webpack 4, which outputs an undefined
`window` reference and causes

```
ReferenceError: window is not defined
```

upon import via e.g. `require("cache-control-parser")` from
node. Updating the webpack config fixes the error after rebuild.
References:

- https://stackoverflow.com/a/58718315
- webpack/webpack#6642
- https://webpack.js.org/configuration/output/#outputglobalobject
antonparussimov added a commit to antonparussimov/vue-flatpicker that referenced this issue Mar 3, 2023
@br0nstein
Copy link

In case this helps anyone, if you are hitting this error in your web worker itself (from your application code using window), you should either update the code to instead use self, or before your other imports in the web worker entrypoint file add an import "./setup" to a setup file that makes a window global: self.window = self

snowMan128 added a commit to snowMan128/next-plugins that referenced this issue Mar 25, 2024
This addresses this comment that the workers plugin is no longer working in next@7:
vercel/next-plugins#218 (comment)

This is rooted in this issue, in which the fix is to configure webpack to handle non-window global objects in the client in order for it to internally handle references to the global:
webpack/webpack#6642

This next plugin is meant to handle files written as WebWorkers, in which `window` as the global is undefined (in lieu of `self`), so I've decided to explicitly fallback to `self` as the global object.

In addition, I've fixed a typo where a bracket was missing in the README.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests