How to handle SharedWorker code upgrades with webpack 5?

1.1k Views Asked by At

Webpack 5 supports building a separate entrypoint for Workers or SharedWorkers just by adding the following code to a file: new SharedWorker(new URL('./worker.js', import.meta.url));

Webpack generates a separate chunk for this worker: 123.s0m3ha2h.esm.js I believe its name contains its content's hash.

When a SharedWorker is instantiated, the browser checks if there is one already with same URL, and if not, starts a new ShraredWorker.

I would like to avoid having 2 versions of my SharedWorker running at the same time after code update. How can one achieve this when using SharedWorkers with webpack?

1

There are 1 best solutions below

2
Tarnay Kálmán On

One can use webpack magic comments for workers:

new SharedWorker(new URL('./worker.ts', import.meta.url) /* webpackChunkName: 'shared-worker.js' */);

This should provide a stable unchanging filename for the SharedWorker, so that only a single instance runs.

As long as any tab is connected to the initially loaded version of the SharedWorker, it will keep running, and code from newer bundles will be connecting to the older SharedWorker.