afeef
afeef

Reputation: 4696

Failed to construct 'Worker': Module scripts are not supported on DedicatedWorker yet in Angular 8

Error

ERROR in node_modules/typescript/lib/lib.dom.d.ts(25,1): error TS6200: Definitions of the following identifiers conflict with those in another file: EventListenerOrEventListenerObject, BlobPart, HeadersInit, BodyInit, RequestInfo, DOMHighResTimeStamp, CanvasImageSource, MessageEventSource, ImageBitmapSource, TimerHandler, PerformanceEntryList, VibratePattern, AlgorithmIdentifier, HashAlgorithmIdentifier, BigInteger, NamedCurve, GLenum, GLboolean, GLbitfield, GLint, GLsizei, GLintptr, GLsizeiptr, GLuint, GLfloat, GLclampf, TexImageSource, Float32List, Int32List, BufferSource, DOMTimeStamp, FormDataEntryValue, IDBValidKey, Transferable, BinaryType, ClientTypes, EndingType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionMode, KeyFormat, KeyType, KeyUsage, NotificationDirection, NotificationPermission, PushEncryptionKeyName, PushPermissionState, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResponseType, ServiceWorkerState, ServiceWorkerUpdateViaCache, VisibilityState, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType node_modules/typescript/lib/lib.dom.d.ts(3473,5): error TS2687: All declarations of 'privateKey' must have identical modifiers. node_modules/typescript/lib/lib.dom.d.ts(3474,5): error TS2687: All declarations of 'publicKey' must have identical modifiers. node_modules/typescript/lib/lib.webworker.d.ts(25,1): error TS6200: Definitions of the following identifiers conflict with those in another file: EventListenerOrEventListenerObject, BlobPart, HeadersInit, BodyInit, RequestInfo, DOMHighResTimeStamp, CanvasImageSource, MessageEventSource, ImageBitmapSource, TimerHandler, PerformanceEntryList, VibratePattern, AlgorithmIdentifier, HashAlgorithmIdentifier, BigInteger, NamedCurve, GLenum, GLboolean, GLbitfield, GLint, GLsizei, GLintptr, GLsizeiptr, GLuint, GLfloat, GLclampf, TexImageSource, Float32List, Int32List, BufferSource, DOMTimeStamp, FormDataEntryValue, IDBValidKey, Transferable, BinaryType, ClientTypes, EndingType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionMode, KeyFormat, KeyType, KeyUsage, NotificationDirection, NotificationPermission, PushEncryptionKeyName, PushPermissionState, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResponseType, ServiceWorkerState, ServiceWorkerUpdateViaCache, VisibilityState, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType node_modules/typescript/lib/lib.webworker.d.ts(85,5): error TS2687: All declarations of 'privateKey' must have identical modifiers. node_modules/typescript/lib/lib.webworker.d.ts(86,5): error TS2687: All declarations of 'publicKey' must have identical modifiers. node_modules/typescript/lib/lib.webworker.d.ts(1074,5): error TS2375: Duplicate number index signature. node_modules/typescript/lib/lib.webworker.d.ts(1360,5): error TS2375: Duplicate number index signature. node_modules/typescript/lib/lib.webworker.d.ts(1434,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'FormData' must be of type '{ new (form?: HTMLFormElement): FormData; prototype: FormData; }', but here has type '{ new (): FormData; prototype: FormData; }'. node_modules/typescript/lib/lib.webworker.d.ts(2170,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'Notification' must be of type '{ new (title: string, options?: NotificationOptions): Notification; prototype: Notification; readonly maxActions: number; readonly permission: NotificationPermission; requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise<...>; }', but here has type '{ new (title: string, options?: NotificationOptions): Notification; prototype: Notification; readonly maxActions: number; readonly permission: NotificationPermission; }'. node_modules/typescript/lib/lib.webworker.d.ts(4322,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'onmessage' must be of type '(this: Window, ev: MessageEvent) => any', but here has type '(this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any'. node_modules/typescript/lib/lib.webworker.d.ts(4332,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'location' must be of type 'Location', but here has type 'WorkerLocation'. node_modules/typescript/lib/lib.webworker.d.ts(4333,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'onerror' must be of type 'OnErrorEventHandlerNonNull', but here has type '(this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any'. node_modules/typescript/lib/lib.webworker.d.ts(4335,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'self' must be of type 'Window', but here has type 'WorkerGlobalScope'. node_modules/typescript/lib/lib.webworker.d.ts(4344,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'.

I have Refrence

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)

app.component.ts

        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.
        }

app.worker.ts

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

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

tsworker.json

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

Tsconfig

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

Angular Docs

There are two important things to keep in mind when using Web Workers in Angular projects:

Some environments or platforms, like @angular/platform-server used in Server-side Rendering, don't support Web Workers. You have to provide a fallback mechanism to perform the computations that the worker would perform to ensure your application will work in these environments.

Running Angular itself in a Web Worker via @angular/platform-webworker is not yet 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)

Solution that worked

  1. In the Chrome browser, type in the web address chrome://flags/.
  2. To turn on CSS Grids, scroll down to Experimental Web Platform features and select enable.
  3. Relaunch Now.

enter image description here

browser setting resolved but errors still present.

Upvotes: 2

Views: 7405

Answers (2)

Johan Swanepoel
Johan Swanepoel

Reputation: 482

You need to stop and restart the app for the new settings to take effect. Until then you will get that browser error.

Upvotes: 3

Kasun Piyumal
Kasun Piyumal

Reputation: 41

Can you post your tsconfig.app.json here? There will be an entry like this,

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

Change it to,

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

And for worker not initialization issue, you need to make sure angular.json is updated correctly and configured to use webworkers. There will be an entry for "webWokerTsConfig". Double check that.

Finally, my config files are like this in the project which the the web worker is working

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"
  ]
}

angular.json should have entries like this in the project workspace you are trying to configure webworkers.

"webWorkerTsConfig": "tsconfig.worker.json"

And this

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

I had the same issue. You have to inspect your config files. This is a issue in misconfiguration. It's not about the browser.

Upvotes: 4

Related Questions