Using Web Workers with Webpack 5

Subscribe to my newsletter and never miss my upcoming articles

Webpack 5 came with native support for Web Workers and made it pretty easy to use them in your application.

To instantiate a worker you have to call its constructor and use the URL-constructor to specify its file path:

const worker = new Worker(new URL("./worker.js", import.meta.url));

Webpack then picks up this syntax and creates a new dependency graph for the worker entry file. That means you can use import-statements in your worker like you're used to. Webpack will do its usual magic to compile these away, so you don't need native support for import in workers, which at the time of writing this is still pretty sparse.

You can also import libraries from npm into your worker, or even use the same utility files that you also use in your main bundle if they are compatible with Web Workers.

If you want to have an easier time working with Web Workers, I recommend using the comlink library. It makes talking to your worker as easy as calling a method on it or accessing a property with async/await. No postMessage needed!

And if you want to learn more about Web Workers in general, check out this talk from Surma. It gives a great introduction to workers and when you should use them.


No Comments Yet