'Creating a web worker inside React
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)
Solution 1:[1]
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
Solution 2:[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>
);
}
}
Solution 3:[3]
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
Solution 4:[4]
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();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | otorrillas |
| Solution 2 | |
| Solution 3 | Heartbit |
| Solution 4 | Abdullah Jamal |
