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:
Do you have any ideas?
Thanks in advance!
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) => {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With