new Worker() will only be bundled if passed a String

Viewed 4384

I'm trying out web workers to run a time-consuming data analysis script in my Angular 8 app, but I'm having some trouble bundling the worker. I'm looking for help to figure out what I'm missing.

I have generated a new worker for my project using the schematics included with Angular-CLI 8.0.2:

ng g webWorker suggestions --project=my-project

This generates a new suggestions.worker.ts and tsconfig.worker.ts, and updates my tsconfig.app.json, angular.json and package.json. These look OK to me, but I can provide details if needed.

I have moved my suggestions.worker.ts to the same folder as the service that will instantiate the worker. The function instantiating the worker looks as follows:

async calculateSuggestions<T>(
    data: T[]
): Promise<Suggestions<T>> {
    const worker = new Worker('./suggestions.worker', {
      type: 'module',
    });

    const result = new Promise((resolve, reject) => {
      worker.onmessage = ({ data }) => {
        resolve(data);
      };

      worker.onerror = ({ error }) => {
        reject(error);
      };
    }) as Promise<Suggestions<T>>;

    worker.postMessage({
      data: data
    });

    return result;
}

However, when I build my project, the following warning and error appear:

WARNING in new Worker() will only be bundled if passed a String.

ERROR in chunk suggestions-suggestions-module
suggestions-suggestions-module.js
{..} \node_modules\@ngtools\webpack\src\index.js! {..} \src\app\extractor\
No template for dependency: ConstDependency

My guess is that I'm not instantiating the Worker correctly, causing the bundling process to fail.

The warning seems to indicate that I should pass a String to the Worker constructor, but I am already doing so.

Further, the path behind the exclamation mark on line 3 of the Error is actually two folders above where I store my service and my worker files. Maybe this is a hint?

Any suggestions will be much appreciated!

3 Answers

I solved this issue by downgrading to angular-cli@8.0.1. Still not sure about the root cause of the issue.

To avoid

... will only be bundled if passed options that include { type: 'module' }.. "
add

new Worker('./testworker.worker', { type: "module" });

To avoid

No template for dependency: ConstDependency
  • Check if there is webpack version mismatch
  • See the output of node ls. There should be two different versions of webpack@4.x.x
  • To fix this either remove your webpack dependency from package.json or try npm prune
  • Remove the 'node_modules' folder and 'package-lock.json'
  • Run npm i
  • Run ng serve or ng build
Related