silx-kit / h5web

React components for data visualization and exploration
https://h5web.panosc.eu/
MIT License
165 stars 17 forks source link

Inline web worker in `H5WasmLocalFileProvider` #1614

Closed axelboc closed 2 months ago

axelboc commented 2 months ago

I faced a bundling issue with the worker when I tried to use H5WasmLocalFileProvider in myHDF5. The worker was compiled as an asset at dist/assets/worker.<hash>.mjs, and imported from the main bundle with new Worker('/assets/worker.<hash>.mjs', ...). Obviously, when importing @h5web/h5wasm from node_modules in myHDF5, this absolute path was problematic...

I found a workaround by letting the consumer instantiate the worker (import LocalWorker from '@h5wasm/h5wasm/worker' and then new LocalWorker()). I had to configure Vite to build the worker independently and add an exports entry to @h5web/h5wasm's package.json. I also had to add a worker prop to H5WasmLocalFileProvider. As I said, it worked, but obviously this added complexity for consumers, which I wasn't happy with...

So instead I decided to just inline the worker into the main bundle of the @h5web/h5wasm package to avoid generating that extra dist/assets/worker.<hash>.mjs module in the first place. At least consumers don't have to do anything for the worker to work :drum:.

Unfortunately, with both these workarounds, the h5wasm package ends up duplicated in the consumer app's bundle if both H5WasmProvider and H5WasmLocalFileProvider are imported. We'll have to wait for Vite to better support the new Worker() syntax in library mode, I guess. Not great, but I'll try to mitigate this issue by importing the providers lazily/dynamically in myHDF5.