How to handle Web Workers "standard" syntax with webpack?

dhar picture dhar · Jan 18, 2016 · Viewed 10.5k times · Source

I wonder if it's actually possible to handle Web Worker "standard syntax" in webpack (e.g var worker = new Worker('my-worker-file.js');) and how?

I know about worker-loader but as far as I understand it needs a specific syntax and is not compatible with the standard one.

In other words, is it possible to bundle that file with webpack without changing the code? -> https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js#L8

With browserify, I would use workerify transform, but I can't find anything in webpack's world.

Answer

Stefan Dragnev picture Stefan Dragnev · Jan 13, 2017

You can configure Webpack to pack your worker js file into a separate bundle. In webpack.config.js:

{
  entry: {
    bundle: './app/main.js',
    worker: './app/my-worker-file.js'
  },
  output: {
    filename: '[name].js'
  }
  ...
}

This way you get two bundles: bundle.js with your main application and worker.js with the worker entrypoint. Then, inside your main bundle, you can do new Worker('worker.js')

worker-loader basically does the same. Whenever something is loaded through it, it creates a separate bundle entry, so to speak, which is automatically named [hash].worker.js. It then stores this file name into the function that is returned from require('worker!...'), which just passes it to new Worker. At the end, it's exactly the same process as I've described above with the only difference that the name of the bundle is managed automatically for you.