How to use Web Workers in create-react-app with worker-loader?

5.9k Views Asked by At

I am trying to implement Web Workers in my React app to share a single WebSockets connection over multiple tabs. I use the worker-loader dependency for loading in Web Workers.

Unfortunately i can't even get a simple dedicated web worker to work.

App.jsx:

import React, { Component } from 'react';

// eslint-disable-next-line
import myWorker from 'worker-loader!./worker.js';

class App extends Component {
  constructor(props) {
    super();

    this.state = {};
  }

componentWillMount() {
    if(window.SharedWorker) {
      console.log(myWorker);
      myWorker.port.postMessage('Hello worker');

      myWorker.port.onmessage = function(e) {
        console.log('Message received from worker');
        console.log(e.data);
      }
    }

worker.js:

onconnect = function(e) {
  var port = e.ports[0];

  port.onmessage = function(e) {
    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
    port.postMessage(workerResult);
  }
}

When loading the page the following webpack error appears:

webpack error I can't use the config style usage of worker-loader because that requires some changes in the webpack config. This config can't be edited because of create-react-app. I could if i eject create-react-app, but that does have some disadvantages.

Why doesn't it work? Somebody any ideas?

Thanks in advance,

Mike

1

There are 1 best solutions below

0
On

As @KevBot indicated i had to create a new instance of the Worker:

// eslint-disable-next-line
import Worker from 'worker-loader!./worker.js';

let myWorker = new Worker();