Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 953
thijsfranck Avatar asked Jun 09 '19 18:06

thijsfranck


1 Answers

The solution is here https://github.com/angular/angular-cli/issues/14776#issuecomment-516998921, so just add the second parameter like below

new Worker("file path", { type: "module" });
like image 173
Leon Avatar answered Nov 10 '22 18:11

Leon