Discussion on angular offering, approaches to integrate web worker in angular (5 and 6) application, their pros and cons. A sample example implementation using custom web worker approach and integrating the same with CLI(1 and 6) and the application.
1. Web Worker in your
Angular Application
By :- Suresh Patidar
September 9, 2018
2. Target audience
This presentation is useful for people who are:
● Creating/defining architecture for their next
generation products.
● Product manager/owner, concerned about the
end user experience and customer
satisfaction.
● Using or planning to use Angular as a
framework for developing the front end of
their products.
● Web developers building high performance
web applications.
● Interested in knowing new web development
trends and how to incorporate some of them
into their products.
3. Assumption
This presentation assumes that you are already familiar
with web development technologies(HTML/CSS/JS/TS)
and architectures(SPA) and have some knowledge
about frameworks implementing these architectures
(like Angular, ReactJS etc.)
4. TOC
● What is Angular and what does it offer?
● What is Angular CLI?
● How to work with web worker in cli project?
● What other choices do we have?
● Example - Angular 5 with angular-cli 1.6.8
● Example - Angular 6 with angular-cli 6.1.5
6. Angular
Angular is a platform that
makes it easy to build
applications with the web.
Angular empowers developers
to build applications that live on
the web, mobile, or the desktop.
7. ● Develop across all platform by reusing your
code and building your apps for any
deployment target.
● Achieve maximum speed and performance
possible on the web platform today.
● Incredible tooling to build features quickly.
Key offering
9. ● A command line interface for building angular
applications
● Responsible for automating away many of
challenges and headaches of developers.
● Makes easier to get started and get moving
quickly with Angular.
Angular CLI
11. ● Angular framework supports running your whole application in Web
Worker.
● Extract webpack configuration file using “eject” feature of CLI-1.
● Install web worker bootstrap dependencies.
● Make changes in UI bootstrap logic. (app.module.ts, main.ts,
workerLoader.ts)
● Update webpack to build your web worker.
● This support require a thorough planning as your application should not
have any direct references to DOM, Window, document or parent in your
typescript code.
Source:- https://blog.angularindepth.com/angular-with-web-workers-step-by-step-dc11d5872135
Working with Web Worker in CLI-1 (Angular 5
or below) Projects
13. Few concerns that we may have with approach discussed in previous slides:
● I have performance problem in just a small part of the project and not the whole
application.
● I don’t want to run whole application in web worker.
● I don’t want to eject from CLI and own whole webpack configuration.
● I am not sure if my application is compatible to run in we web worker and also not in
a position to fix incompatibilities (if any).
● I want to have a better control on what to run and what not to run in web worker.
In order to address these concerns, let’s plan to implement web worker as an
independent piece of code and integrate the same with CLI and the
application.
In following slides we will create a sample application implementing web
worker, integrating it to CLI and finally to our application.
Other choices
15. Disclaimer
This example presents one of the way to integrate web worker in Angular application and may
not be the only and best way to do so. The way of integrations are largely depends on the
application need, use case and other external/internal environmental constraints. The example I
am going to create in subsequent slides is purely based on my online research and past
experience.
16. What are we going to implement?
In order to demonstrate the integration of web worker in Angular application, we
will create a simple angular app using angular-cli. The app will have only one
component created by default. We will add couple of interactive UI animations and
few buttons to trigger processing in web worker and non web worker mode and
feel the performance and responsiveness of the browser UI.
To mock the CPU intensive processing we will implement a simple function that
takes a duration as parameter and enter in a while loop for the given duration. It
returns the number of iterations done in the loop.
17. Angular version used for Example
01
We are going to implement this example using both Angular 5
and Angular 6.
We are doing this for both versions because of the difference in
the angular-cli used to create these projects. Angular 5
application is created using angular-cli version 1.6.8 and the
Angular 6 applications is created using angular-cli version 6.1.5.
The way projects are created and built using these CLIs are quite
different.
Feel free to refer only the example that matches your project
requirement and skip the other.
18. Development Environment Used
● Windows 10 pro 64 bit operating system
● NodeJS v8.9.3
● NPM v5.5.1
● Angular Cli v1.6.8 for example 1 and v6.5.8 for example 2
● Visual Studio Code v1.25.1
This is just an information about the environment used and you can always use
your own environment for the development, provided framework and libraries used
are compatible.
19. NGULAR 5 (5.2.0)
NGULAR CLI 1 (1.6.8)
First Implementation of the Example
Note:- Focus more on understanding of this example. You can download complete code
of this example from github:- https://github.com/patidar-suresh/angular5-webworker
20. Create new Angular 5 App using CLI
Open a command prompt from your working directory and
create new angular 5 application using command “ng new
angular5-webworker --style=scss”.
This command will create a directory named “angular5-
webworker”, download project structure and install all the
dependencies required for your project.
21. Let’s first create a folder structure for our worker. Create a folder called “worker” at same
level as “src”. This folder will hold all the code for workers implementation.
Folder structure for worker:
main.worker.ts
app.workers.ts
Topic?
cpu-
intensive.work
er.ts
image-
processing.w
orker.ts
22. Now create a file “main.worker.ts” as the first entry point for our worker. It create a new
instance of AppWorkers and listen for messages from parent. It also pass the received
messages to app workers for further processing.
main.worker.ts
app.workers.ts
Topic
?
cpu-
intensive.wo
rker.ts
image-
processing.wor
ker.ts
23. Create a file “app.workers.ts”. It will hold the logic to distribute the work based on topic. It
is also responsible to return the message back to the parent.
main.worker.ts
app.workers.ts
Topic
?
cpu-
intensive.wo
rker.ts
image-
processing.wor
ker.ts
24. Create a file “cpu-intensive.worker.ts” to implement our first worker which will hold the
logic to perform cpu intensive work by entering in a while loop for given duration.
main.worker.ts
app.workers.ts
Topic
?
cpu-
intensive.wo
rker.ts
image-
processing.wor
ker.ts
25. Create “worker-message.model.ts” and “worker-topic.constants.ts” under shared folder.
These are shared model and constants used across the workers and worker clients.
worker-message.model.ts
worker-topic.constants.ts
26. We are done with
creating worker code!!!
Now let’s configure
webpack to build it for us.
27. Create a custom webpack config file (webpack.worker.config.js) that will
build web worker code using angular-cli. You may notice that we asked
webpack to build and create bundle in “src/assets/workers” directory.
28. Modify package.json and add few scripts for development convenience. Here we are using node
module “concurrently” for watching worker changes concurrently with app code changes. Install
“concurrently” by running command “npm install concurrently --save-dev”
29. We are all set :)
Let’s start using web
worker in our application.
30. Create a service called “worker.service.ts” under src/app directory. This service will be
responsible for initializing web worker and delegating the work to it.
32. Modify “app.component.html” and “app.component.scss” and add above html and scss content
to it. Here we have added an animated flying bird and input box to echo the message typed into
it. We also have buttons to start processing in different modes.
app.component.scss
app.component.html
33. Modify “app.component.ts” to add properties, logic and handlers. This component uses the
worker service to perform cpu intensive calculation in web worker. For non worker mode similar
calculation logic is coded in component itself.
34. Let’s start the application using command “npm start”. You will see a command output similar to
mentioned above. Open browser and enter http://localhost:4200 to see the application live.
Try run processing in different mode and experience the performance and responsiveness.
Complete code of this example is available at- https://github.com/patidar-suresh/angular5-
webworker
35. NGULAR 6 (6.1.0)
NGULAR CLI 6 (6.1.5)
Second Implementation of the
Example
Note:- Focus more on understanding of this example. You can download complete code
of this example from github:- https://github.com/patidar-suresh/angular6-webworker
36. Create new Angular 6 App using CLI
Open a command prompt from your working directory and
create new angular 6 application using command “ng new
angular6-webworker --style=scss”.
This command will create a directory named “angular6-
webworker”, download project structure and install all the
dependencies required for your project.
37. Since we don’t have any have changes in worker logic
between Angular 5 and Angular 6, so you can create the
worker same as mentioned in earlier slides:
● Create worker folder structure (Slide #21)
● Create main worker (Slide #22)
● Create app worker (Slide #23)
● Create cpu intensive worker (Slide #24)
● Create shared model and constants (Slide #25)
38. We have created worker
code!!!
Now let’s configure Angular
CLI to build it for us.
39. Before we start configuration, let’s see
what’s new in Angular Cli 6?
● Support for libraries and multiple applications
○ Create libraries of a set of component,directives, pipes and services to
share.
○ Create several applications in same cli project (called workspace)
● A new architecture
○ Broken down into small pieces
○ New “Architect” package
○ New configuration file (“angular.json”)
● New Schematics.
● Webpack 4 under the hood.
● Better error stacks and reduced installation time.
40. How to customize Angular CLI 6 build?
● In Angular cli 1.x we had “ng eject’ but in Angular cli 6 it has been
disabled temporarily.
● CLI 6 has new concept called builders. With builders we can customize
the build process.
● We can define our own builders or use one of the builder provided by
community.
41. Let’s modify “angular.json” and add builder (“build-worker” & “serve-worker”) for our worker code
by using angular builder (“@angular-devkit/build-angular:server”). Now running command “ng run
angular6-webworker:build-worker” should generate worker bundle in src/assets/workers.
42. Modify package.json and add few scripts for developer convenience. Here we are using node
module “concurrently” for watching worker changes concurrently with app code changes. Install
“concurrently” by running command “npm install concurrently --save-dev”
43. Since we neither changed worker logic nor its usage between
Angular 5 and Angular 6, so you can modify your app to use web
worker in similar way as done in earlier slides:
● Create worker service(Slide #30) , Few RXJS related changes to accommodate:
○ Replace all the rxjs imports with “import { Subject, Observable, Subscription,
fromEvent } from 'rxjs';”
○ Update workerPath to “assets/workers/main.js”
○ Change “Observable.fromEvent(“ to just “fromEvent(“
● Modify app module to provide service (Slide #31)
● Modify app component html and scss (Slide #32)
● Modify component ts file (Slide #33)
● Run the application using “npm start” (Slide #34)
44. Can’t see the result when you start
processing in web worker mode?
So let’s investigate...
45. Do you see some error in console like below image?
Some searching on google and stackoverflow, revealed that typescript(2.7.2)
is adding “exports” to the bundle file (main.js).
Older version of typescript(2.1.6) solved the exact same issue, but we don’t
have option to use the older version as Angular 6 requires the latest one.
Removing “exports” from the first line of main.js file, seems to be fixing this
issue. So let’s use this hack until this gets fixed in typescript.
46. But how do we implement this hack in an elegant way?
Angular CLI 6 Builders to Rescue!
Here is the implementation plan:
● Install “custom-webpack” builder.
● Install “replace-in-file-webpack-plugin”
● Create custom webpack config.
● Modify “angular.json” to use custom webpack config.
47. Install builder for custom-webpack by command “npm install @angular-builders/custom-
webpack --save-dev”. Also install replace-in-file-webpack plugin using command “npm install
replace-in-file-webpack-plugin --save-dev”
48. Create custom webpack file (webpack.webworker.config.js) in the root directory of your
application. In this additional configuration we just need to define what we need for extra
functionalities. Other default functionalities will take configuration from CLI automatically.
49. Modify “angular.json” and update the builders for worker to use custom-webpack builder and provide
appropriate configurations. You can optionally define “configurations” for “production” build as
needed. I have skipped them here.
Complete code of this example is available at- https://github.com/patidar-suresh/angular6-webworker
50. We are done with changes!
Run “npm start” and open url http://localhost:4200 in
the browser to access the application.
Note:- Make sure to get rid of the hack that we just implemented,
once you get a proper fix for typescript error.