Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 694
dhar Avatar asked Jan 18 '16 09:01

dhar


1 Answers

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.

like image 166
Stefan Dragnev Avatar answered Sep 18 '22 06:09

Stefan Dragnev