I am working on a JavaScript application that will do some computation on the client side (inside the browser). However, the computation is later to be found quite expensive, and running them in the main thread will block the UI. So I decided to run them in the web worker.
Since the logic for the computation is already written in JavaScript modules and bundle with webpack (they are typescript modules as part of a react app, to be exact), the most natural approach is to use worker with type module
. However, as in 2022, this feature is not supported in older browsers, in particular, Firefox does not support it. This prevents me from using this feature.
With only the classic worker, the only solution I can came up with is to copy all these modules (and their dependency) into a single js file, which will be a nightmare for maintainability. Are there any way to workaround this issue (for example, generate this single js file programmatically without messing with existing code)? In particular, since I am using webpack, I thought about creating a separate bundle of all the module code for the worker. But I am not familiar with webpack enough to try that.
CodePudding user response:
WebPack version 5 offers worker support out of the box.
It's relatively easy to include worker-loader
to get something similar working in Webpack version 4.
However, if the goal is to have a conversation with the web worker (i.e. passing parameters, getting results), then it might be worth looking into Google's comlink
or even integrating the comlink-loader
into your webpack configuration.
Comlink makes WebWorkers enjoyable. Comlink is a tiny library (1.1kB), that removes the mental barrier of thinking about postMessage and hides the fact that you are working with workers.