Search code examples
javascriptwebpackecmascript-6workeres6-modules

JS - creating new worker causes 404


I'm using Worker API to create new worker, it's as simple as:

var myWorker = new Worker('src/worker.js');

Unfortunately I'm using webpack to build my project and linking to src/worker.js returns 404.

How can I use it to create my Worker?

import hardWorker from './src/hardWorker.js';
var myWorker = new Worker(HOW TO PUT HARDWORKER HERE?);

Solution

  • Try using the worker-loader plugin for webpack, which can be found here: https://github.com/webpack-contrib/worker-loader

    This registers scripts loaded through it as a Web worker, and bundles all of your workers in the main bundle that webpack creates. Using it in your app is as simple as this:

    import MyWorker from 'worker-loader!./Worker.js';
    const worker = new MyWorker();
    

    Or you can add loader configuration parameters to your webpack.config so all files matching a specific pattern are loaded and registered as workers. The worker-loader has an example of this.