Búsqueda de sitios web

typescript - Error al construir 'Worker': Los scripts de módulo aún no son compatibles con DedicatedWorker en 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'.    

Tengo referencia

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

Documentación de Angular

Hay dos cosas importantes que tener en cuenta al usar Web Workers en proyectos de Angular:

Algunos entornos o plataformas, como @angular/platform-server utilizado en la Renderización del lado del servidor, no soportan Web Workers. Debes proporcionar un mecanismo de respaldo para realizar los cálculos que el worker realizaría para asegurar que tu aplicación funcione en estos entornos.

Ejecutar Angular en sí mismo en un Web Worker a través de @angular/platform-webworker aún no es compatible con 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)
  • ¿Alguien puede guiarme sobre cómo solucionar este problema de web workers?

Solución que funcionó

  1. En el navegador Chrome, escribe en la barra de direcciones web chrome://flags/.
  2. Para activar CSS Grids, desplázate hacia abajo hasta Funciones experimentales de la plataforma web y selecciona habilitar.
  3. Reiniciar ahora.

browser setting resolved but  errors still present.

Respuesta #1

¿Puedes publicar tu tsconfig.app.json aquí? Habrá una entrada como esta,

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

Cámbialo a

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

Y para el problema de no inicialización del trabajador, necesitas asegurarte de que angular.json esté actualizado correctamente y configurado para usar webworkers. Habrá una entrada para "webWorkerTsConfig". Verifícalo dos veces.

Finalmente, mis archivos de configuración son así en el proyecto en el que el trabajador web está funcionando

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 debería tener entradas como esta en el espacio de trabajo del proyecto que estás intentando configurar con webworkers.

"webWorkerTsConfig": "tsconfig.worker.json"

Y esto

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

Tuve el mismo problema. Tienes que inspeccionar tus archivos de configuración. Esto es un problema de configuración incorrecta. No tiene que ver con el navegador.

Respuesta #2

Necesitas detener y reiniciar la aplicación para que los nuevos ajustes tengan efecto. Hasta entonces recibirás ese error del navegador.