1

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 Answer 1

2

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) => {};
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.