Creating a web worker inside React

dnmh picture dnmh · Nov 24, 2017 · Viewed 16.3k times · Source

I have a React app created with create-react-app, not ejected. I'm trying to use web workers. I've tried the worker-loader package (https://github.com/webpack-contrib/worker-loader).

If I try worker-loader out of the box (import Worker from 'worker-loader!../workers/myworker.js';), I get the error message telling me that Webpack loaders are not supported by Create React App, which I already know.

Would the solution be to eject the app (which I'd prefer not to do) and edit the webpack.config.js or is there some other way of using web workers inside a React app?

EDIT: I have found the solution here: https://github.com/facebookincubator/create-react-app/issues/1277 (post by yonatanmn)

Answer

dnmh picture dnmh · Nov 27, 2017

As I've written in the EDIT of my question above, I've found the solution here: https://github.com/facebookincubator/create-react-app/issues/1277

This is a working example:

// worker.js
const workercode = () => {

    self.onmessage = function(e) {
        console.log('Message received from main script');
        var workerResult = 'Received from main: ' + (e.data);
        console.log('Posting message back to main script');
        self.postMessage(workerResult);
    }
};

let code = workercode.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));

const blob = new Blob([code], {type: "application/javascript"});
const worker_script = URL.createObjectURL(blob);

module.exports = worker_script;

Then, in the file that needs to use the web worker:

import worker_script from './worker';
var myWorker = new Worker(worker_script);

myWorker.onmessage = (m) => {
    console.log("msg from worker: ", m.data);
};
myWorker.postMessage('im from main');