alewin / useWorker

⚛️ useWorker() - A React Hook for Blocking-Free Background Tasks
https://useworker.js.org/
MIT License
2.96k stars 99 forks source link

example for using remote web worker ( stockfish js) #93

Open hunght opened 3 years ago

hunght commented 3 years ago

i try to use this lib https://github.com/nmrugg/stockfish.js/ as a web worker, but it not working. could you have the same example which using normal web worker like postMessage and onmessage, thanks in advance

alewin commented 3 years ago

Of course, in the next few days I'll try to look at it

alewin commented 3 years ago

HI @zant I was preparing a demo with "stockfish.js"

const demoFn = () => {
  var stockfish = STOCKFISH();
  .....
};

function App() {
  const { addToast } = useToasts();

  const [ worker, { status, kill } ] = useWorker(demoFn, {
    remoteDependencies: [
      "https://cdn.jsdelivr.net/npm/stockfish@11.0.0/src/stockfish.min.js"
    ]
  });

I noticed that the sotckfish library uses by default a communication with "postMessages": API Docs. Even if it would work it wouldn't make sense to call

stockfish.postMessage ("go depth 15 ");

inside demoFN.


Proposal

I thought that we could make available the possibility to import a webworker file as well.

const [ worker, { status, kill } ] = useWorker("stockfish.js")

Obviously, if you want to use this feature, you will have to modify your webpack configuration https://webpack.js.org/loaders/worker-loader/

What do you think about it? 🤔

zant commented 3 years ago

Killer feature! @alewin

Looks really good to me, with good docs on the webpack thingy I think it's good to go 👍

Also, FWIW there's an ongoing proposal (Stage 1) on JS module blocks it will basically let us inline modules in code and pass them around as they were files. So if that gets through we will have two ways of doing this, with lots of other cool stuff :)