Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack worker-loader - import doesn't work

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?

like image 283
Yomansk8 Avatar asked Oct 19 '22 04:10

Yomansk8


1 Answers

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.

like image 166
Tomáš Zato - Reinstate Monica Avatar answered Oct 27 '22 09:10

Tomáš Zato - Reinstate Monica