GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.
Apache License 2.0
11.26k stars 386 forks source link

not working in react #437

Open hosseind2 opened 4 years ago

hosseind2 commented 4 years ago

I tested all examples in a react application but it don't works how can I use it in react?

worker.js

import * as Comlink from 'comlink';

async function callbackFunction(cb) {
  await cb("A string from a worker");
}

Comlink.expose(callbackFunction);

index.ts

import * as Comlink from 'comlink';

function callback(value) {
  alert(`Result: ${value}`);
}
async function init() {
  const remoteFunction = Comlink.wrap(new Worker("worker.js"));
  await remoteFunction(Comlink.proxy(callback));
}
init();

for example I call this but it does not execute

surma commented 4 years ago

This is a fairly straight forward example of Comlink that should definitely work (my tests pretty much have this example).

Can you provide a reproduction case? My hunch is that you are using create-react-app or something and I think they compile down to ES5 which might break things.

hosseind2 commented 4 years ago

actually yes, our project is created by create-react-app and yes it compiles down to es5

dominique-mueller commented 4 years ago

Comlink actually does work in React just fine, but there is a bit of setup necessary to get Web Workers running in React first, especially when using create-react-app.

@hosseind2 I have a repository you can take a look at, it contains an example React app that uses Web Workers both in a vanilla kind of way and based on Comlink - the README contains details on how to set it up. Link: https://github.com/dominique-mueller/react-web-worker-experiment

hosseind2 commented 4 years ago

thanks @dominique-mueller