How to work with web workers (use a web worker IN cli project)
Bug 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.
@michaeljota I was wondering if you could provide an example how to do what you suggest
@shlangus I'll try to setup something this weekend and see how it goes. Any idea what to use in a web worker?
This may help:
https://github.com/UIUXEngineering/web-worker-in-ng
On Tue, Apr 17, 2018, 2:25 PM Michael De Abreu [email protected] wrote:
@shlangus https://github.com/shlangus I'll try to setup something this weekend and see how it goes. Any idea what to use in a web worker?
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/angular/angular-cli/issues/5885#issuecomment-382111827, or mute the thread https://github.com/notifications/unsubscribe-auth/AAU0o__3nxJqroYx__2Bqot-TwpsZv4Qks5tpkGTgaJpZM4M3gw8 .
-- Jerry Orta UI / UX Engineer
@jerryorta-dev Thank you, I've already seen checked this as well as all the solutions in this tread =) It uses an approach with separate webpack config and build step for worker. I described something like that at the beginning. But @michaeljota is talking about something different and I'm just curious to see one more approach
My apologies @shlangus, didn't realize I've been on this thread from my phone. I am curious too if this can be done with the cli.
@shahata I actually like the work that @jerryorta-dev did. Still, I think that you can do the same with plain old Javascript, and avoid the additional webpack build process.
I had a similar issue a while back, here is how i solved it :
I added my worker files in the assets folder and referenced them within my angular service as follows:
const worker = new Worker('../assets/jsworkers/analyzer.js');
worker.postMessage({ x_data: mydata });
worker.addEventListener('message', function (e) {...})
Hope it helps someone.
I have just reread the initial post and realized that it is not obvious how worker file is built there. So basically, if you worker is a js file you can use it in the way @creamylooks wrote and I suppose that is what @michaeljota was talking about. But, for example, my case is a worker contains dozens classes written in typescript and contains dependencies such as lodash, rxjs and so on. And I want to be able to process it (compile, minify) in the same way as it is done for whole angular app and that is what worker-loader do.
i was looking for a easy way to outsource some expensive functions from within my angular controlers etc. stumbled over this little gem... seems great for some use-cases: http://www.eslinstructor.net/vkthread/
@jbgarr I think I have exactly the same problem. I am migrating AngularJS application that had some web workers due to really heavy computations.
I found a workaround in webworkify-webpack package. I hope it helps.
However, I would really love to see the official support for "standalone" web workers from Angular CLI as well.
@shlangus I have found a way to run it
app.ts
import GroupWorker from '!worker-loader!ts-loader!./group.worker';
typings.d.ts
declare module "!worker-loader*" {
class WebpackWorker extends Worker {
constructor();
}
export default WebpackWorker;
}
group.worker.ts
import { BoardSettings } from '!ts-loader!../model/board.model';
import { Issue } from '!ts-loader!../model/issue.model';
const ctx: Worker = self as any;
ctx.onmessage = (ev: MessageEvent) => {
But have some cache and compilation performance. Compiler always write: ERROR in ../projects/web/src/app/board/group.worker.ts(1,31): error TS2307: Cannot find module '!awesome-typescript-loader!../model/board.model'. ../projects/web/src/app/board/group.worker.ts(2,23): error TS2307: Cannot find module '!awesome-typescript-loader!../model/issue.model'.
But: chunk {main} main.js, main.js.map (main) 3.12 MB [initial] [rendered] ℹ 「wdm」: Compiled successfully.
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:
"projects": {
"your-worker-name": {
// ...
"architect": {
// ...
"build": {
"builder": "@angular-devkit/build-webpack:webpack",
"options": {
"webpackConfig": "webpack.config.js"
}
}
}
Create a simple webpack config, which builds the worker script to your dist directory, e.g.:
const path = require('path');
const config = {
entry: './src/your-worker.js',
mode: 'production',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'your-worker.js'
}
};
module.exports = config;
Step 2. include the generated worker script in your Angular app
In angular.json, add to your Angular project:
"scripts": [
{ "input": "dist/your-worker.js", "lazy": true }
]
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 and ng build:
"scripts": {
"ng": "ng",
"start": "ng run your-worker-name:build && ng serve",
"build": "ng run your-worker-name:build && ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}
Step 4: profit!
export class AppComponent {
ngOnInit(): void {
const worker = new Worker('your-worker.js');
}
}
I will double check this, but I think that by using Webpack loaders, you'll be fine using Typescript files for the source of the worker.
@michaeljota I did't try that yet. But I guess then you also need to include a typescript loader, as you have a custom webpack config. I didn't want to maintain a huge webpack config. ;)
@dirkluijk That is a great solution and something I will use. As an experiment, I wonder how other new Angular 6 CLI features may enhance the architecture -- such as generating the worker code as another app or lib? That may over-engineer this solution for your app. It's just a thought for larger apps.
@dirkluijk Thank you for your example. I do not see why the scripts array inside angular.json should contain the file? I write the compile worker.js into the assets folder, but maybe that is an anti-pattern in Angular? I can load it fine without its addition to the scripts array.
I have Typescript source, and while it does work, the compiler complains about main.ts accessing the document. That is weird and I could not get rid of the error, since the main.worker.ts does not import anything and does not accesss the DOM. Below is my TS config, where I removed DOM from the libs array.
This is from my project https://github.com/sladiri/web-worker-angular-v7
// webpack.base.config.js
const path = require("path");
module.exports = ({ production = false, ie11 = false }) => ({
mode: production ? "production" : "development",
entry: "./src/main.worker.ts",
// entry: ["../src/polyfills.ts", "./worker/main.worker.ts"],
output: {
path: path.resolve(__dirname, "assets", `webworkers${ie11 ? "-ie11" : ""}`),
filename: "main.worker.js",
},
resolve: { extensions: [".ts"] },
module: {
rules: [
{
test: /\.ts$/,
loader: "ts-loader",
options: {
compilerOptions: {
baseUrl: "./",
outDir: `./dist/out-tsc/worker${ie11 ? "-ie11" : ""}`,
sourceMap: true,
declaration: false,
module: "esnext",
moduleResolution: "node",
emitDecoratorMetadata: true,
experimentalDecorators: true,
target: ie11 ? "es5" : "es2015",
typeRoots: ["node_modules/@types"],
lib: ["es2018", "esnext.asynciterable", "webworker"],
},
},
},
],
},
});
There is actually a package for this:
https://www.npmjs.com/package/ngx-web-worker
I've tried it and it works as far as I can tell.
@dirkluijk great and quick solution 👏👏👏
I am wondering if you tried with contenthash or do you have any thought about it
I have tried implementing a version of the solution given by @jerryorta-dev into an Angular 6 library. I used the worker-loader! Webpack Loader hoping to get the Worker as part of a reusable functionality I am packing into an Angular Library.
That approach just wouldn't work. Finally I found this: https://github.com/angular/angular-cli/issues/5885#issuecomment-302802124. Angular Libraries are packaged using ngpackgr which does not use Webpack and hence there is no support for loaders.
What's more, they also discuss the possibility of Angular CLI moving away from Webpack completely. That means that there would be no supported means to deploy standalone web-workers in Angular CLI. All discussion tends to point to the fact that the entire Angular Application can be run in a web-worker. However, that approach wouldn't work if we need to use some libraries (example: D3) which need access to the DOM.
@kiranjholla What that comments points out is that actually Angular CLI has moved from a building system in the past (From SystemJS to Webpack) and the CLI is all about abstract the build job in a way that the developer can have a consisten behavior.
The solution @dirkluijk post in his comment should work, as long as Angular implement Webpack.
However, I really doubt that they are moving to another building system any time soon. Even if they did, as this is now, I'm sure this would still work, as you are just using another builder task.