Import a module in web worker in reactjs

Viewed 161

i have the following code in worker.js and i am trying to import KMeans inside of it, and i export the worker as shown.

import KMeans from "tf-kmeans";

const splitText = () => {
  ...
    const kmeans = new KMeans({});
  ...
  };
};

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

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

export default worker_script;

In the main component where i want to call the worker, i call it using the following:

let worker = new Worker(new URL(worker_script, import.meta.url), {
      type: "module",
    });

but when i use the worker i get the following error:

Uncaught ReferenceError: tf_kmeans__WEBPACK_IMPORTED_MODULE_1___default is not defined

How can this be solved? TIA

1 Answers

I figured it out using worker-loader. Implement your worker.js as the following:

import KMeans from "tf-kmeans";

onmessage = function (event) {
  // worker body
  //self.postMessage(resultToReturn);
};

then in your main component

  1. import the Worker using worker loader using the following: import Worker from "worker-loader!./kmeans.worker.js";. you may add // eslint-disable-next-line import/no-webpack-loader-syntax to avoid linting problems.
  2. instantiate the worker: var worker = new Worker();
  3. To send anything to the worker use: worker.postMessage({key:value});
  4. To get anything from the worker use: worker.onmessage = (ev) => {};
Related