developit/workerize-loader

What the difference between this package and worker-loader?

anatoly314 opened this issue · 1 comments

Hi,
Can something please point me what the difference between this package and worker-loader?
It looks like both do the same job in a little different way to write workers themself, but I might be wrong.
Thank you.

workerize-loader is like worker-loader, except it reflects methods exported by a module so that they can be called from the main thread.

With worker-loader:

// add-worker.js
onmessage = e => {
  if (e.data.op == 'add') {
    postMessage(add(...e.data.values))
  }
}

function add(a, b) {
  return a+b
}
import worker from 'worker-loader!./add-worker.js'

const inst = worker()
inst.postMessage({ op: 'add', values:[2, 3] })
inst.onmessage = e => {
  console.log(e.data) // 5
}

With workerize-loader:

// add-worker.js
export function add(a, b) {
  return a+b
}
import worker from 'workerize-loader!./add-worker.js'

const inst = worker()
inst.add(2, 3).then(result => {
  console.log(result) // 5
}

The difference is that workerize uses a tiny RPC implementation to make functions callable. While the above example is trivial, using RPC becomes very important when you have multiple calls to a worker function - they can be received and respond in any order, which means postMessage is not sufficient.