How to work with web workers (use a web worker IN cli project)
See original GitHub issueBug Report or Feature Request (mark with an x
)
- [ ] bug report -> please search issues before submitting
- [X] feature request
Versions.
@angular/cli: 1.0.0 node: 6.9.1 os: darwin x64 (macOS Sierra 10.12.3)
Is there a way to import and use a web worker in a component using angular-cli? I’m trying to incorporate a web worker that I wrote into my project, but I’m not having any luck. The web worker worked fine in my project before attempting to convert it to use the CLI (previous version was based on System.js). I’m trying to import my web worker code like this:
import * as MyWorker from 'assets/workers/dropdown.worker.js';
and then I’m trying to create my actual worker instance like this:
let blob = new Blob(['(this.onmessage=', MyWorker.toString(), ')'], { type: "text/javascript" });
let dropdownWorker = new Worker((<any>window).URL.createObjectURL(blob));
The above does not work though, and if I log MyWorker right after I try to import it I see it’s just an empty object instead of a function (which is what it is in my other app). Any help on this would be much appreciated!
UPDATE
I just want to clarify what I’m trying to do: I want to use an existing web worker IN my Angular app, not run my whole app IN a web worker. I know there is separate issue already that relates to the trying to run an entire app in a web worker. These are similar, but very different issues.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:31
- Comments:72 (17 by maintainers)
This is my workaround.
Step 1. Add a custom webpack build to Angular CLI
Since Angular 6 you can use the Angular CLI for custom webpack builds.
Add to
angular.json
:Create a simple webpack config, which builds the worker script to your dist directory, e.g.:
Step 2. include the generated worker script in your Angular app
In
angular.json
, add to your Angular project:Step 3: make sure to build your worker script first…
Just run:
$ ng run your-worker-name:build
And/or modify your package.json to run before
ng serve
andng build
:Step 4: profit!
Example
Here is a proof of concept project for Angular 4 loading web workers: web-worker-in-ng
@jbgarr, I was able to create an Angular 4.x project that implements two web workers, transpiles them, and hashes them in a build. No
ng eject
. The only “gotcha” I forgot to document in the project is the Web Worker JS file can not be the same name as it’s TS file if they reside in the same directory. The webpackworker-loader
gets confused and loads thets
file even when explicitely telling it to load the.js
file.