We are unable to create a 'Worker' as Module scripts are not yet supported on DedicatedWorkers in Angular 8

Error

An error has occurred in the following files: node_modules/typescript/lib/lib.dom.d.ts and node_modules/typescript/lib/lib.webworker.d.ts. Definitions of various identifiers conflict with those in other files, leading to modifier conflicts and duplicate number index signatures.

I have a reference for this issue at:

https://angular.io/guide/web-worker

PS D:\angular-tour-of-heroes> ng generate web-worker app
 CREATE tsconfig.worker.json (212 bytes)
 CREATE src/app/app.worker.ts (157 bytes)
 UPDATE src/tsconfig.app.json (295 bytes)
 UPDATE angular.json (4990 bytes)

In your app.component.ts file:

        if (typeof Worker !== 'undefined') {
          // Create a new
          const worker = new Worker('./app.worker', { type: 'module' });
          worker.onmessage = ({ data }) => {
            console.log(`page got message: ${data}`);
          };
          worker.postMessage('hello');
        } else {
          // Web Workers are not supported in this environment.
          // You should add a fallback so that your program still executes correctly.
        }

Your app.worker.ts code:

        /// <reference lib="webworker" />

        addEventListener('message', ({ data }) => {
          const response = `worker response to ${data}`;
          postMessage(response);
        });

Update your tsworker.json file:

        {
          "extends": "./tsconfig.json",
          "compilerOptions": {
            "outDir": "./out-tsc/worker",
            "lib": [
              "es2018",
              "webworker"
            ],
            "types": []
          },
          "include": [
            "src/**/*.worker.ts"
          ]
        }

And your main tsconfig file:

            {
              "extends": "../tsconfig.json",
              "compilerOptions": {
                "outDir": "../out-tsc/app",
                "baseUrl": "./",
                "module": "es2015",
                "types": []
              },
              "exclude": [
                "test.ts",
                "**/*.spec.ts",
                "**/*.worker.ts"
              ]
            }

Important information from Angular Docs:

When using Web Workers in Angular projects, keep in mind that some environments or platforms may not support them (like @angular/platform-server). Providing a fallback mechanism is crucial. Running Angular itself in a Web Worker via @angular/platform-webworker is currently not supported in Angular CLI.

            main.js:1305 Uncaught TypeError: Failed to construct 'Worker': Module scripts are not supported on DedicatedWorker yet. You can try the feature with '--enable-experimental-web-platform-features' flag (see https://crbug.com/680046)
                at Module../src/app/app.component.ts (main.js:1305)
                at __webpack_require__ (runtime.js:79)
                at Module../src/app/app.module.ngfactory.js (main.js:1332)
                at __webpack_require__ (runtime.js:79)
                at Module../src/main.ts (main.js:10012)
                at __webpack_require__ (runtime.js:79)
                at Object.0 (main.js:10034)
                at __webpack_require__ (runtime.js:79)
                at checkDeferredModules (runtime.js:46)
                at Array.webpackJsonpCallback [as push] (runtime.js:33)
  • If you are facing issues with Web Workers, here's how to fix it:
  1. In Chrome browser, go to chrome://flags/.
  2. Enable Experimental Web Platform features under Experimental Web Platform options.
  3. Relaunch the browser.

https://i.stack.imgur.com/Eb6XT.png

The browser setting might resolve some issues, but errors could still persist.

Answer №1

Could you kindly share your tsconfig.app.json file? Look for an entry similar to this one,

"exclude": [
        "src/**/*.worker.ts"
]

Please update it to,

"exclude": [
        "**/*.worker.ts"
]

To resolve the worker initialization issue, ensure that your angular.json is correctly updated and configured to utilize webworkers. Check for the "webWorkerTsConfig" entry and verify it.

Here are the configurations from a project where the web worker is functioning properly:

tsconfig.json

{
    "compileOnSave": false,
    "compilerOptions": {
    "baseUrl": "./",
    "downlevelIteration": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts",
    "**/*.worker.ts"
  ]
}

tsworker.worker.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/worker",
    "lib": [
      "es2018",
      "webworker"
    ],
    "types": []
  },
  "include": [
    "src/**/*.worker.ts"
  ]
}

Ensure that your angular.json contains entries like these when setting up webworkers in your project workspace:

"webWorkerTsConfig": "tsconfig.worker.json"

Also include this,

"tsConfig": [
          "src/tsconfig.app.json",
          "src/tsconfig.spec.json",
          "tsconfig.worker.json"
],

I faced a similar problem before. It's crucial to review your configuration files as this issue is typically caused by misconfiguration rather than being browser-related.

Answer №2

In order for the new settings to be applied, it is necessary to stop and restart the application. During this time, you may continue to encounter the browser error.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...

Error in ThreeJS: Unable to execute material.customProgramCacheKey

I encountered an issue TypeError: material.customProgramCacheKey is not a function The error pops up when I invoke the function this.animate(). However, no error occurs when the URL is empty. Where could this error be originating from since I don't ...

"What are the necessary components to include in UserDTO and what is the reasoning behind their

Presenting the User entity: package com.yogesh.juvenilebackend.Model; import jakarta.annotation.Generated; import jakarta.persistence.*; import lombok.*; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor public class ...

Struggling with the compilation of this Typescript code

Encountering a compile error: error TS2339: Property 'waitForElementVisible' does not exist on type 'signinPage' SigninPage code snippet: export class signinPage{ constructor(){ emailInput: { selector: 'input[type ...

Leverage HighCharts on numerous occasions

Hello there, I'm curious about utilizing the Highcharts library in my Angular application. I have 3 tabs (sale / rental / rental & sale), each with 3 identical diagrams that display different data from my API. Currently, my setup only works on t ...

IdentityServer4: The authentication time is not specified

I'm currently working on an angular (asp.net core) application that utilizes an identityserver4 server for authentication. Initially, the login process works seamlessly, displaying the login form and returning both the id_token and access_token. How ...

Is there a way to incorporate an external JavaScript file into a .ts file without the need for conversion?

I have an external JavaScript file that I need to utilize in a .ts file without performing any conversion. Does anyone know how to use it within TypeScript without the need for conversion? ...

The function cannot be accessed during the unit test

I have just created a new project in VueJS and incorporated TypeScript into it. Below is my component along with some testing methods: <template> <div></div> </template> <script lang="ts"> import { Component, Vue } from ...

Combining various outcomes into a single entity for ion-slide in Ionic 2

I am facing a similar issue with this problem, but with a different twist. I want to showcase three results in ion-slide, and while iDangero Swipper seems like a solution, I believe ion-slide could also achieve something similar to this. Please take a look ...

Do Angular routes need to have distinct prefixes?

I have defined two routes. /apples---> AppleComponent, /apples/:id ---> AppleDetailComponent, When I visit /apples/111, it will first go into AppleComponent and then into AppleDetailComponent. What steps should I take to make it only match /appl ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

What could be causing the "no exported member" errors to appear when trying to update Angular?

The dilemma I'm facing a challenge while attempting to upgrade from Angular V9 to V11. Here are the errors that I am encountering: Namespace node_module/@angular/core/core has no exported member ɵɵFactoryDeclaration Namespace node_module/@angular/ ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Navigating to the end of a list using Angular's scroll feature

I'm trying to figure out how to automatically scroll to the bottom of a list in TypeScript, can someone help me with this? Here's a similar example I found that uses jQuery (I specifically need it in TypeScript): Scroll to bottom of list wit ...

What is the process for appending an attribute to a DOM element?

Is there a way to conditionally add the multiple attribute to this element? <mat-select [formControlName]="field.name" multiple> I attempted to do so with the following: <mat-select [formControlName]="field.name" [attr.multiple]="field?.mu ...

Is there a way to optimize app speed in Angular2 by importing CommonModule and RouterModule in a centralized location?

I find myself constantly importing these two modules in almost every component: import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; Is there a way to import them only once in the global app. ...

Encountering a issue while running npm start with Angular 2 RC build

After upgrading from Angular2 beta 15 to the RC version, I encountered some errors while trying to run my application. typings/browser/ambient/es6-shim/index.d.ts(8,14): error TS2300: Duplicate identifier 'PropertyKey'. typings/browser/ambient/e ...

Can dynamic forms in Angular 2 support nested forms without relying on formBuilder?

I'm familiar with implementing nested forms in reactive form, but I'm unsure about how to do it in dynamic form within Angular 2. Can nested forms be implemented in dynamic forms in Angular 2? ...

Every time I attempt to install a package, I encounter an NPM unmet peer dependency issue

Entering the complex world of NPM for the first time has been quite a challenge. After running create-react-app, the installation process is almost complete except for some warning messages: yarn add v1.17.3 [1/4] Resolving packages... warning react-scri ...

Angular app experiences a breakdown due to a JitCompiler issue

After being given the responsibility of enhancing a project, I diligently added new modules and components. However, upon running the application, it crashes. Uncaught Error: Component EnquiryComponent is not part of any NgModule or the module has not bee ...