18

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)

5 Answers 5

27

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

2 Comments

the problem is that you cannot import any function into the blob.
Unexpected use of 'self' no-restricted-globals
3

For webpack 5 onwards you can use web workers without using worker-loader or any bundler in simple way, https://webpack.js.org/guides/web-workers/

I managed to run my web worker in same way.

In the file you want to import web worker

// here ./deep-thought.js is the path to the web worker

const worker = new Worker(new URL('./deep-thought.js', import.meta.url));

worker.postMessage({
  question:
    'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
});
worker.onmessage = ({ data: { answer } }) => {
  console.log(answer);
};

In the web worker file,

// just to show it supports importing files into web worker in generic way

import JSONstream from 'JSONStream';

 self.onmessage = function (e) {
   // worker code inside

   // just to show it supports importing and using files into web worker in generic way

   const jsonParser = JSONstream.parse();
 }

2 Comments

does this work after the app has been built? This only works for me in development..
yes it worked for me after build
2

Yes, it is possible to use custom webpack config through using custom-react-scripts.

To use custom-react-scripts in your existing create-react-app project, as explained in this issue, what you need to do is:

  • Remove react-scripts from package.json:

    "devDependencies": {
        "react-scripts": "0.6.1"
    },
    
  • Run npm install --save-dev *your-custom-react-scripts*

For a more detailed explanation, have a look at @kitze's article and his own custom-react-scripts, that include built-in support for features like:

  • Decorators
  • babel-preset-stage-0
  • Less
  • Sass
  • CSS modules
  • Sass modules
  • Less modules
  • Stylus modules

1 Comment

Thanks for the tip. It is handy to know something like this is possible. In the meantime, I've found a simpler solution (please see my EDIT above).
2

Complimenting dnmh's answer, this comment in the github issue works perfect if you are experiencing problems with "this", "self", "window" subjects...

In my case following solved all my troubles:

You don't need to touch this file, just keep it.

//WebWorkerEnabler.js
export default class WebWorkerEnabler {
    constructor(worker) {
         let code = worker.toString();
         code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));

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

This is where you run your background tasks

// WebWorker.js
export default function WebWorker(args) {
    let onmessage = e => { // eslint-disable-line no-unused-vars
         // THIS IS THE PLACE YOU EMBED YOUR CODE THAT WILL RUN IN BACKGROUND        
         postMessage("Response");
    };
}

And here is the connection of WebWorker with the rest of your code. You send and receive data to WebWorker from below componentDidMountfunction.

//BackgroundTaskRunner.js
import * as React from 'react';
import WebWorkerEnabler from './WebWorkerEnabler.js';
import WebWorker from './WebWorker.js';
const workerInstance = new WebWorkerEnabler(WebWorker);
export default class BackgroundTaskRunner extends React.Component {
    componentDidMount(){
        workerInstance.addEventListener("message", e => {
            console.log("Received response:");
            console.log(e.data);
        }, false);
        workerInstance.postMessage("bar");
    }
    render() {
        return (
                <React.Fragment>
                    {"DEFAULT TEXT"}
                </React.Fragment>
        );
    }
}

Comments

0

Follow these steps in order to add your worker files to your create-react-app project.

1. Install these three packages:

$ yarn add worker-plugin --dev
$ yarn add comlink
$ yarn add react-app-rewired --dev

2. Override webpack config:

In your project's root directory create a config-overrides.js file with the following content:

const WorkerPlugin = require("worker-plugin");

module.exports = function override(config, env) {
    //do stuff with the webpack config...

    config.plugins = [new WorkerPlugin({ globalObject: "this"}), ...config.plugins]
    return config;
}

3. Replace your npm scripts inside package.json by:

"start": "react-app-rewired start",
"build": "react-app-rewired build",

4. Create two files in order to test your configuration:

worker.js

import * as Comlink from "comlink";

class WorkerWorld {
  sayHello() {
    console.log("Hello! I am doing a heavy task.")
    let numbers = Array(500000).fill(5).map(num => num * 5);
    return numbers;
  }
}

Comlink.expose(WorkerWorld)

use-worker.js

import * as Comlink from "comlink";

const initWorker = async () => {
    const workerFile = new Worker("./worker", { name: "my-worker", type: "module" });
    const WorkerClass = Comlink.wrap(workerFile)

    const instance = await new WorkerClass();
    const result = await instance.sayHello();
    console.log("Result of my worker's computation: ", result);
}
initWorker()

5. See the output:

$ yarn start

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.