webpack-contrib / worker-loader

A webpack loader that registers a script as a Web Worker
MIT License
1.46k stars 273 forks source link

Allow per-instance or per-worker-code options (such as name or constructor type) without explicit webpack rules #312

Open ghost opened 3 years ago

ghost commented 3 years ago

(I'm still new to web-development and webpack, so please inform me if any of the following is already possible somehow!)

Expected Behavior / Situation

1. Using arguments in constructor of generated Worker (Ideal solution):

import MyWorker from "./my.worker.js";

var i = 0;
var worker_0 = new MyWorker(Worker, {name: `Worker ${i}`});
i++;
var worker_1 = new MyWorker(Worker, {name: `Worker ${i}`});

or (TypeScript-ish):

[...]
var worker_0 = new MyWorker<Worker>({name: `Worker ${i}`});
[...]

New workers should show up as "Worker 0" and "Worker 1" in debugger. Remaining problems:

2. Using placeholder in webpack configuration (Acceptable solution):

{
  test: /\.worker\.js$/,
  loader: 'worker-loader',
  options: {
    worker: {
      type: "Worker",
      options: {
        name: "[name]"
      }
    }
  }
}
import MyWorker from "./my.worker.js";

var i = 0;
var worker_0 = new MyWorker();
i++;
var worker_1 = new MyWorker();

New worker should show up as "my" or "my.worker" in debugger. Remaining problems:

Actual Behavior / Situation

  1. Two workers with randomized blob names will be created; the arguments are ignored.
  2. Two workers with the name "[name]" will be created; the placeholder is not replaced.

Modification Proposal

It should be made easier to name or fine-tune workers, without explicitly listing them in webpack rules.

This will ease debuggability. We have a couple of different workers (some of which also run the same code), so giving explicit names will help to find them more quickly. Chrome will display the workers name in its debuggers, but we don't seem to have a good way to add per-instance information to the name. We also don't seem to have the option to reflect what code the worker is running without writing explicit rules to differentiate between different worker-code files.

Ideally this would be done in a way that allows per-instance settings. To achieve this, workers should respect constructor arguments (potentially fill-in / override existing option fields from webpack configuration), so per-instance settings can be applied. The arguments could be equivalent to webpack worker.type and worker.options This is also similar to how it is done normally: https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/name#example

As an alternative acceptable solution, we could drop the per-instance requirement, but at least have a per-worker-code solution, so at least workers using different code can be differentiated. This could be achieved using placeholders in the webpack configuration. This doesn't solve our initial issue, but would already be a vast improvement.