1

I am trying to use angular 8 jit compler in WEB WORKER but getting an error while trying to import the Compiler module or any other angular module in web-worker.ts file

/// <reference lib="webworker" />
import {Compiler } from '@angular/core';

addEventListener('message', ({ data }) =>
 {
  let response = `worker response to ` + data  ;


});       

node_modules/@angular/core/core.d.ts:13052:20 - error TS2304: Cannot find name 'Document'.

Igor
  • 60,821
  • 10
  • 100
  • 175
  • Searching on the error message I found this: [Typescript cannot find name window or document](https://stackoverflow.com/a/41336998/1260204) – Igor Oct 16 '19 at 13:22

1 Answers1

1

Web worker doesn't have any access to the DOM, so the document object on the window isn't available for you or any other imported module. See this quote from this well-explained answer by T.J. Crowder:

Service workers — web workers in general — don't have direct access to the DOM at all. Instead, have the worker post the information to the main thread, and have code in the main thread update the DOM as appropriate. The threading model for JavaScript on browsers is that there is only one main UI thread (the default one your in-page code runs on), which can access the DOM. The others are walled off from it.

In addition, don't forget to configure your worker as module type:

@Injectable()
export class SomeWorkerService {
  private readonly worker = new Worker('./custom.worker', { type: 'module' }); 
  ...
}
Zeev Katz
  • 2,273
  • 2
  • 16
  • 42
  • Is there a way than to use Angular compiler (need to JIT components) in web workers? import {Compiler } from '@angular/core'; – user2894836 Oct 17 '19 at 16:03