4

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

Maikkeyy
  • 1,017
  • 1
  • 11
  • 18
  • 1
    Looks like you still need to create a new instance of the worker: `new myWorker()` – KevBot Jun 09 '18 at 21:33
  • That was it! Thank you! After a lot of trying I totally missed this. I now however get the error: myWorker.port is undefined. Do you know why this error is thrown? Thanks in advance! – Maikkeyy Jun 09 '18 at 22:08

1 Answers1

2

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();
Maikkeyy
  • 1,017
  • 1
  • 11
  • 18