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

2
  • 1
    Looks like you still need to create a new instance of the worker: new myWorker() Commented Jun 9, 2018 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! Commented Jun 9, 2018 at 22:08

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.