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

Enable the Angular button only when the radio button has been selected

Just starting out with Angular and I have a query. This is a scenario for my project at work. https://i.stack.imgur.com/R3SxA.png In this screenshot, I want to enable the "ajouter" button when at least one radio button is selected in the secure chest (s ...

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

I am experiencing difficulties with my Angular 8 NPM package as it is unable to locate its own

I am encountering an issue where my assets are successfully copied over to my scoped npm package, but they are not available after the application is served. Currently, the images in my application are searching for a path like this: https://localhost:420 ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Using a Typescript typeguard to validate function parameters of type any[]

Is it logical to use this type of typeguard check in a function like the following: Foo(value: any[]) { if (value instanceof Array) { Console.log('having an array') } } Given that the parameter is defined as an array o ...

Essential parameters needed in a Typescript function signature

My code includes the following type definition: type FuncWithRequiredParams = (a: number, b: number, c:string) => void const func1: FuncWithRequiredParams = (a: number, b: number, c: string) => {} // This is functional const func2: FuncWithRequiredP ...

Gatsby struggles with generating Contentful pages using TypeScript

I have been working on creating dynamic pages with Contentful in Gatsby + Typescript. While I am able to fetch data successfully using GraphQL in a browser, I encounter issues when trying to fetch data in gatsby-node.ts. The pages seem to be generated part ...

Using TypeScript to retrieve a strongly typed promiseValue from an angular $modalInstanceA

New to TypeScript Question: I'm working on returning a strongly typed promise from angular's $modalInstance. Here is an example of what I have: this.$modal.open(options).result.then(result => { At the moment, 'result' is of typ ...

Implement Cross-Origin Resource Sharing in Angular frontend

I am facing an issue with two microfrontends running on different ports (4200 and 4201) where one frontend is unable to access the translation files of the other due to CORS restrictions. To overcome this obstacle, I created a custom loader in my code that ...

What steps are required to transition an Angular application developed without the Angular CLI into an Angular CLI project?

I've created an Angular app using tools like NPM (without utilizing the Angular CLI). What would be the most efficient way to transition this project into the CLI project structure? I want to have the ability to utilize commands like ng serve. ...

Navigating resolvedUrl with getServerSideProps in the newest version of NextJS - a comprehensive guide

Is there a way to obtain the pathname without using client-side rendering? I have been searching for information on how to utilize the getServerSideProps function, but so far with no luck. Initially, I attempted to employ usePathname; however, this result ...

Stopping the infinite refresh issue in your React webpack application

Every time I modify the TS file, Webpack keeps refreshing the page without stopping. The console message reads: "@ebpack 5.66.0 compiled successfully" I've searched online and experimented with various plugins, but none of them seem to solve the issu ...

In TypeScript and React, what is the appropriate type to retrieve the ID of a div when clicked?

I am facing an issue in finding the appropriate type for the onClick event that will help me retrieve the id of the clicked div. const getColor = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => { const color = event.target.id; // ...

Only map property type when the type is a union type

My goal is to create a mapping between the keys of an object type and another object, following these rules: Each key should be from the original type If the value's type is a union type, it should have { enum: Array } If the value's type is not ...

Migrating from AngularJS to the latest version, Angular12, may present some challenges such as the error message: "Unable to resolve

Currently, I am in the process of migrating from AngularJS 1.8.2 to angular 12. After transitioning from grunt to webpack for compilation, my next step is tackling the actual migration to Angular. My initial goal is to have Angular and AngularJS coexist si ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

Can someone guide me on creating a slideshow using Ionic?

Having trouble integrating a javascript/css slideshow into Ionic. Ionic does not support the use of ".style" in elements. Need assistance, below is the code: <head> <title>Slideshow</title> <style> .slides {display:none;} </styl ...

Function parameter constrained to a specific property of a generic type T

In my codebase, I have a custom function called uniqBy, which filters out duplicate items based on a specified key: export function uniqBy<T>(array: T[], key: any): T[] { const seen = {}; return array.filter(function (item) { if (item ...

Angular 2 component hierarchy with parent and child components

Currently, I am in the process of learning typescript and angular2. My attempt to incorporate parent and child components into my fiddle has not been successful. Despite conducting some research, I have encountered an error that states: Uncaught ReferenceE ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...