angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Feat: Run angular in web worker mode

Open k3nsei opened this issue 10 years ago β€’ 65 comments

In current setup there is no possibility to bootstrap angular in web worker mode. Please add this killer functionality.

k3nsei avatar Sep 23 '16 09:09 k3nsei

@dipaktelangre check out @fedeee comment about Angular with Web Workers Step by step

yuvalbl avatar Jun 07 '18 21:06 yuvalbl

I waiting for this for a long time, this can improve any apps performance significantly. Although we have managed to handle it manually that would be nice if the Angular team can support it out of the box in Angular/cli.

BTW, would be nice if Angular team can share their discussions here, maybe someone (for instance myself) can help to send a PR and help to get this done quicker.

mhadaily avatar Jul 10 '18 16:07 mhadaily

ng eject no longer works; is there any hope of accomplishing this with angular-cli-builders?

fr0 avatar Aug 13 '18 20:08 fr0

Any news on that? I have a table of a lot of heavy OnPush components, everything works fine, except for when they are initiated at first β€” would love to show loader spinning while they do, but for it to not freeze the UI they need to initialize in a worker.

waterplea avatar Sep 04 '18 13:09 waterplea

Could that be helpful to a smooth integration with the CLI? https://github.com/GoogleChromeLabs/worker-plugin

maxime1992 avatar Sep 23 '18 22:09 maxime1992

No news about this??? 😴😴😴😴

mhosman avatar Nov 12 '18 19:11 mhosman

Having the choice to do it would be really nice

cedvdb avatar Jan 27 '19 02:01 cedvdb

@maxime1992 there's ongoing work to add that plugin in https://github.com/angular/angular-cli/pull/12575.

filipesilva avatar Jan 28 '19 15:01 filipesilva

One of the problems is when you load modules and material2 animations get stuck.

mhosman avatar Jan 28 '19 18:01 mhosman

Material2 works with DOM manipulation, so it won't run in a web worker.

michaeljota avatar Jan 28 '19 20:01 michaeljota

Yes, but maybe the loading of the modules could be done in a web worker.

mhosman avatar Jan 28 '19 21:01 mhosman

Any news on that? people are existed with that feature.

Serginho avatar Feb 13 '19 15:02 Serginho

with the ng eject command removed, there's no way to load the workderLoader file.. considering that @angular/platform-webworker and @angular/platform-webworker-dynamic are part of angular there's literally no way to use them as a developer at the moment with the new cli version. I'd expect them to work with the cli by default.. Perhaps an ng add @angular/platform-webworker command could do.

Are there any updates/workarounds and how to do this considering that ejecting is not possible anymore? this was one of the most exciting features about angular that was show cased in ng-conf when angular2 was first released.

khaledosman avatar Feb 20 '19 13:02 khaledosman

@khaledosman I've been trying to implement this for a little while. I got some results but it's still a work in progress. Here is what I've been doing so far:

npm install --save-dev @angular-builders/custom-webpack

src/main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { bootstrapWorkerUi } from '@angular/platform-webworker';

import {AppModule} from './app/app.module';
import {environment} from './environments/environment';

if (environment.production) {
  enableProdMode();
  bootstrapWorkerUi('webworker.bundle.js');
}

else {
  document.addEventListener('DOMContentLoaded', () => {
    platformBrowserDynamic().bootstrapModule(AppModule);
  });
}

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser'
import { WorkerAppModule } from '@angular/platform-webworker'

const AppBootstrap =
	environment.production
	? WorkerAppModule
	: BrowserModule.withServerTransition({ appId: 'myApp' })

imports: [
	...
	AppBootstrap
]

angular.json

      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
                "path": "./webpack.client.config.js",
                "mergeStrategies": {

                }
             },

webpack.client.config.js

const path = require('path');
const webpack = require('webpack');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { AngularCompilerPlugin } = require('@ngtools/webpack');

module.exports = {
  entry: {
    webworker: [
      "./src/workerLoader.ts"
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      excludeChunks: [
        "webworker"
      ],
      chunksSortMode: "none"
    }),
    new AngularCompilerPlugin({
      mainPath: path.join(__dirname, "src/main.ts"),
      tsConfigPath: path.join(__dirname, "src/tsconfig.app.json"),
      entryModule: path.join(__dirname, "src/app/app.module#AppModule"),
      exclude: ['./server.ts']
    })
  ],
  optimization: {
    splitChunks: {
      name: "inline"
    }
  }
}

src/workerLoader.ts

import 'polyfills.ts';
import '@angular/core';
import '@angular/common';

import { platformWorkerAppDynamic } from '@angular/platform-webworker-dynamic';
import { AppModule } from './app/app.module';

platformWorkerAppDynamic().bootstrapModule(AppModule);

Running bg build produces the following error: ERROR in : TypeError: Cannot read property 'getTypeChecker' of undefined

If I remove the AngularCompilerPlugin in the custom webpack file, it does compile successfully but the client can't find app-root.

If anybody here figures something out, let me know. I'll keep digging.

glemiere avatar Feb 25 '19 19:02 glemiere

Hey guys! I got this to work with Angular7!

Here is copy of my StackOverflow answer:

Good news guys, I got this to work with Angular 7! πŸŽ‰πŸŽ‰πŸŽ‰

Requirement: npm install --save-dev @angular-builders/custom-webpack html-webpack-plugin Make sure that you have production:true in your env file if you just want to copy/past the code below.

Step 1: Edit your angular.json file the following way:

"architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
                "path": "./webpack.client.config.js",
                "replaceDuplicatePlugins": true
             },
            ...
          }

You are only editing the build part because you don't really need the whole worker thing in dev server.

Step 2: Create webpack.client.config.js file at the root of your project. If you're not using SSR, you can remove exclude: ['./server.ts'],

const path = require('path');
const webpack = require('webpack');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { AngularCompilerPlugin } = require('@ngtools/webpack');

module.exports = {
  entry: {
    webworker: [
      "./src/workerLoader.ts"
    ],
    main: [
      "./src/main.ts"
    ],
    polyfills: [
      "./src/polyfills.ts"
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      excludeChunks: [
        "webworker"
      ],
      chunksSortMode: "none"
    }),
    new AngularCompilerPlugin({
      mainPath: "./src/main.ts",
      entryModule: './src/app/app.module#AppModule',
      tsConfigPath: "src/tsconfig.app.json",
      exclude: ['./server.ts'],
      sourceMap: true,
      platform: 0
    }),
  ],
  optimization: {
    splitChunks: {
      name: "inline"
    }
  }
}

Step 3: Edit you AppModule:

import { BrowserModule } from '@angular/platform-browser'
import { WorkerAppModule } from '@angular/platform-webworker'
const AppBootstrap =
			environment.production
			? WorkerAppModule
			: BrowserModule.withServerTransition({ appId: 'myApp' })
	imports: [
		...
		AppBootstrap,
        ...
    ]

Step 4: Edit you main.ts file.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { bootstrapWorkerUi } from '@angular/platform-webworker';

import {AppModule} from './app/app.module';
import {environment} from './environments/environment';

if (environment.production) {
  enableProdMode();
  bootstrapWorkerUi('webworker.bundle.js');
}

else {
  document.addEventListener('DOMContentLoaded', () => {
    platformBrowserDynamic().bootstrapModule(AppModule);
  });
}

Step 5: It will compile just fine, but you may have a runtime issue due to DOM manipulation in your app. At this point you just have to remove any DOM manipulation and replace it by something else. I'm still working at figuring this part out and will edit my answer later to give direction about this issue.

If you're not doing savage DOM manipulation, then you're good to go with a free main-thread and auditing your app using lighthouse should not show Minimize main-thread work anymore, as most of your app except UI loads in a second thread.

glemiere avatar Feb 27 '19 03:02 glemiere

@glemiere it gives me webworker.bundle.js not found where I can find webworker.bundle.js ? Thanks

LeonBarroso avatar Mar 13 '19 15:03 LeonBarroso

@glemiere good work.

Is angular official support for this ever gonna be a thing ?

cedvdb avatar Mar 19 '19 08:03 cedvdb

platform-webworker deprecated https://github.com/angular/angular/pull/30642

bmayen avatar May 24 '19 01:05 bmayen

Indeed @bmayen it's not officially deprecated in v8 https://github.com/angular/angular/commit/361f181

That is a huge disappointment. We were all very excited about this. To let everybody know, it is still possible to run parts of your code inside a webworker to make multi-threading possible. I just wish Angular had at least offered the possibility to run services or anything web crawlers don't care much about in separate threads.

I will be digging into making a library to make this behavior possible and developer friendly, any help is welcome. Thanks everybody for the hard workπŸ’ͺ

glemiere avatar Jun 10 '19 05:06 glemiere

Running Angular itself in a Web Worker (via @angular/platform-webworker) is indeed deprecated. But it is now easier to run parts of your app in a Web Worker using https://angular.io/guide/web-worker.

filipesilva avatar Jun 10 '19 12:06 filipesilva