How to create a NPM package that utilizes a web worker?

32 Views Asked by At

I'm trying to create an npm package that utilizes a web worker that is of type module. The problem is that the React application I've linked my package to for testing can't find the worker.js file. It's looking for it at http://localhost:3000/worker.js, but the worker is located inside my package, and my package is locally linked to the React app. How would I go about adding a worker to my npm package?

I tried using WebPack, but that just brought a whole bunch of additional issues to a simple problem of telling my package about this static worker file.

1

There are 1 best solutions below

0
Miguel Myers On

I figured out the issue. I just needed to load the worker by a URL object and call toString() method.

new Worker(new URL('./worker.js', import.meta.url).toString(),{ type: "module" })