I am making an application with React/Webpack/ES6 and I have a problem.
I'm trying to use web workers to make API calls. I have a functional thread pool to iniate my web workers and there are no problems with that.
The problem is that I am using the webpack worker-loader to create my workers and if I want to import an external library like this:
import MyLibrary from './path/to/MyLibrary';
I got an error like this:
Uncaught ReferenceError: window is not defined
I can't make it work, but according to the documentation, I think that I'm doing it right. Any idea?
Well, you didn't share any code that might be problematic with MyLibrary
. Normally, JavaScript error objects contain info about line and file where the error was thrown.
Nevertheless, I will take a guess about the obvious posibility: You're using window
in MyLibrary
. The window
global property is not defined in web workers! For code that has to be worker compatible, use self
. It will also work in normal browser context - self
is therefore preferable to window
.
As a side note, also do not rely on window
not being defined in worker - some libraries define it to deal with compatibility problems. I do this too, sometimes:
if(typeof window != "object")
self.window = self;
This is also acceptable workaround if you can't or don't want to edit the library. I did exactly this and much more to make jQuery work in web workers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With