As of webpack 5, you can useWeb Workers withoutworker-loader.
newWorker(newURL('./worker.js',import.meta.url));// or customize the chunk name with magic comments// see https://webpack.js.org/api/module-methods/#magic-commentsnewWorker(/* webpackChunkName: "foo-worker" */newURL('./worker.js',import.meta.url));The syntax was chosen to allow running code without bundler, it is also available in native ECMAScript modules in the browser.
Note that while theWorker API suggests thatWorker constructor would accept a string representing the URL of the script, in webpack 5 you can only useURL instead.
Using a variable in theWorker constructor is not supported by webpack. For example, the following code will not work:const url = new URL('./path/to/worker.ts', import.meta.url); const worker = new Worker(url);. This is because webpack cannot analyse the syntax statically. It is important to be aware of this limitation when usingWorker syntax with webpack.
src/index.js
const worker=newWorker(newURL('./deep-thought.js',import.meta.url));worker.postMessage({ question:'The Answer to the Ultimate Question of Life, The Universe, and Everything.',});worker.onmessage=({ data:{ answer}})=>{ console.log(answer);};src/deep-thought.js
self.onmessage=({ data:{ question}})=>{ self.postMessage({ answer:42,});};Similar syntax is supported in Node.js (>= 12.17.0):
import{ Worker}from'worker_threads';newWorker(newURL('./worker.js',import.meta.url));Note that this is only available in ESM.Worker in CommonJS syntax is not supported by either webpack or Node.js.