Search code examples
angulartypescriptweb-worker

How to import a typescript module inside a Web Worker in angular 8?


Since Angular 8, you can now generate web worker to your app from the CLI. I did so exactly like the official guide:

https://angular.io/guide/web-worker

And it works perfectly.

But as soon as I try to import any module to the top of app.worker.ts with:

import { MyData } from '../shared/shared.module';

Then I get compile errors: enter image description here

Is there any other way to import modules into web workers?


Solution

  • My problem was that this shared module I was trying to import was created with ng generate module. In doing so, angular automatically imports NgModule, CommonModule and adds an @NgModule with declarations and imports to the exported class. These give you access to the DOM, and web workers cannot have access to the DOM. Which is what the compile error I was getting was talking about. Even tho I wasn't really using these imports and none of these were the reason why I was importing this module into the webworker. They were there anyway and they were causing the error.

    I fixed it by simply removing the 2 import statements for NgModule, CommonModule and the whole @NgModule from my shared module. Then it imported fine without any errors into the web worker.