Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WebWoker with create-react-app and typescript

I'm having the project using create-react-app and typescript

I would like to enable WebWorker to do some expensive tasks. But I have not found any solutions to enable it.

I have looked through some libraries:

  • https://github.com/developit/workerize-loader

Do you have any ideas?

Thanks in advance!

like image 438
Tan Dat Avatar asked Dec 31 '22 03:12

Tan Dat


1 Answers

I finally use [worker-loader]. It works OK.

https://github.com/webpack-contrib/worker-loader#integrating-with-typescript

To integrate with TypeScript, you will need to define a custom module for the exports of your worker

// typings/custom.d.ts
declare module "worker-loader!*" {
  class WebpackWorker extends Worker {
    constructor();
  }

  export default WebpackWorker;
}
// Worker.ts
const ctx: Worker = self as any;

// Post data to parent thread
ctx.postMessage({ foo: "foo" });

// Respond to message from parent thread
ctx.addEventListener("message", (event) => console.log(event));
// App.ts
import Worker from "worker-loader!./Worker";

const worker = new Worker();

worker.postMessage({ a: 1 });
worker.onmessage = (event) => {};

worker.addEventListener("message", (event) => {});
like image 86
Tan Dat Avatar answered Jan 13 '23 20:01

Tan Dat