问题
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'.
回答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' });
...
}
来源:https://stackoverflow.com/questions/58414352/using-angular-modules-in-web-workers