Web Workers

As of webpack 5, you can use Web Workers without worker-loader.

Syntax

new Worker(new URL('./worker.js', import.meta.url));

The syntax was chosen to allow running code without bundler since using this is available in native ECMAScript modules in the browser (https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker). In webpack, the worker.js file that the new Worker API call refers to and the files that worker.js imports are additionally bundled.

Example

src/index.js

const worker = new Worker(new URL('./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


import getAnswer from './answer';
self.onmessage = ({ data: { question } }) => {
  self.postMessage({
    answer: getAnswer(),
  });
};

src/answer.js


export default function getAnswer() {
  return 42;
}

In this case, deep-thought.js and answer.js will be bundled for use in the web worker.

Node.js

Similar syntax is supported in Node.js (>= 12.17.0):

import { Worker } from 'worker_threads';

new Worker(new URL('./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.

1 Contributor

chenxsan