Angular CLI: dev and prod builds with JiT and AoT

I’m happy to announce that my colleague Anton and I started working on the second edition of our Angular book published by Manning. The new TOC is here. The major changes in the second edition are:

– Get rid of any mention of SystemJS – use Angular CLI only
– Replace the chapter on Webpack with the chapter on ngrx
– Add more code samples illustrating various features and techniques

I just finished re-writing the first chapter and would like to offer you a fragment that illustrates the use of Angular CLI for creating dev and prod builds. Your feedback is appreciated.

To make this article more practical, generate a new project Hello CLI using Angular CLi:

ng new hello-cli

Then build the bundles, start the dev server and open the browser on port 4200 by running a single command:

ng serve -o

Now goes the chapter fragment.

Production Builds

The ng serve command bundled the app files but didn’t optimize our Hello CLI application. Open the Network tab in the dev tools of your browser and you’ll see that the browser had to load 2.4MB to render this simple app. In dev mode, the size of the app is not a concern because you run the server locally and it takes the browser only 802 milliseconds to load this 2.4MB of code as shown below.

Now visualize a user with a mobile device browsing the Internet over a regular 3G connection. It’ll take 10 seconds to load the same Hello CLI app. Many people can’t tolerate waiting for 10 seconds for any app except Facebook (30% of the Earth population just lives on Facebook). We need to reduce the size of the bundles before going live.

Applying the -prod option while building the bundles will produce much smaller bundles by optimizing your code, i.e. it’ll rename your variables into single-letter ones, will remove comments and empty lines, and will remove the majority of the unused code. There is another piece of code that can be removed from the app bundles – the Angular compiler. Yes, the ng serve command included such compiler into the vendor.bundle.js. In the next section will talk about production builds and how to remove the Angular compiler from your deployed app.

JiT and AoT Compilations

Take a look at the code of the generated app.component.html.

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAw...">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="http://angularjs.blogspot.com/">Angular blog</a></h2>
  </li>
</ul>

For the most part, it consists of standard HTML tags, but there is one line that browsers won’t understand:

Welcome to {{title}}!

These double curly braces represent binding a value into a string in Angular, but this line has to be compiled by the Angular compiler (it’s called ngc) to replace the binding with something that browser would understand. A component template can include another Angular-specific syntax (e.g. structural directive *ngIf and *ngFor) that need to be compiled before asking the browser to render the template.

When you run the ng serve command, the template compilation is performed inside the browser. After the browser loads your app bundles, the Angular compiler (packaged inside vendor.bundle.js)performs the compilation of the templates from main.bundle.js. This is called Just-in-Time (JiT) compilation. This term means that the compilation happens in time of the arrival of the bundles to the browser.

The drawbacks of the JIT compilation are:

1. There is a time gap between the loading bundles and rendering the UI. This time is spent on JiT compilation. On a small app like Hello CLI this time is minimal, but in real world apps, the JiT compilation can take a couple of seconds, so the user needs to wait longer for just seeing your app.

2. The Angular compiler has to be included in the vendor.bundle.js, which adds to the size of your app.

Using the JiT compilation in the prod is discouraged, and we want the templates to be pre-compiled into JavaScript before the bundles are created. This is what Ahead-of-Time (AoT) compilation is about.

The advantages of the AoT compilation are:

1. The browser can render the UI as soon as you app is loaded. There is no need to wait for code compilation.

2. The ngc compiler is not included in the vendor.bundle.js and the resulting size of your app might be smaller.

Why use the word “might” and not “will”? The removing of ngc compiler from the bundles should always result in smaller app size? Not always. The reason being that the compiled templates are larger than those that use a concise Angular syntax. The size of the Hello CLI will definitely be smaller as there is only one line to compile. But in larger apps with lots of views, the compiled templates may increase the size your app so it’s even larger than the JIT-compiled app with ngc included in the bundle. But you should use the AoT mode anyway because the user will see initial landing page of your app sooner.

Creating bundles with the -prod option

When you build the bundles with the -prod option, Angular CLI performs code optimization and AoT compilation. Let’s see it in action by running the following command in our Hello CLI project:

ng serve -prod

Open the app in your browser and check the Network tab as shown in the next image. Now the size of the same app is only 120KB (compare to 2.4MB) and the load time is 573 milliseconds (compare to 802 milliseconds).

What a great result! Google home page weighs more than 200KB. As a matter of fact, the size of the app could be reduced even more after applying the gzip compression to the bundles. Note that the file names of the bundles now include a hash code of each bundle. Angular CLI calculates a new hash code on each prod build to prevent browsers from using the cached version if a new app version is deployed in prod.

Recently released Angular CLI 1.3.0 offers a new option –build-optimizer, which does a better job in eliminating unused code. Even in our simple app it reduced the size of this app to 111Kb. On larger apps the effect of this option can be even bigger. In one of our apps that uses Angular Material it reduced the app size from 290KB to 200KB (lots of dead code there?). The option –build-optimizer works with both ng serve and ng build commands.

ng serve -prod --build-optimizer

Shouldn’t we always use AoT? Ideally, you should unless you use some third-party JavaScript libraries which produce errors during the AoT compilation. If you run into this problem, turn the AoT compilation off by building the bundles with the following command:

ng serve -prod -aot=false

The next screen shot shows that both the size and the load time increased compared to the AoT compiled app.

We were using the ng serve -prod command, which was building the bundles in memory. If you’re ready to generate prod files, use the ng build -prod command instead. We’ll go over the process of building production bundles and deploying the app on the server in chapter 8.

The goal of this section was to get you started with Angular CLI, and we’ll continue its coverage in chapter 2.

Advertisements

Angular CLI: multiple apps in the same project

You may need to have an Angular project that has multiple apps so you can run the build of a particular app, say depending on the customer you’re preparing the build for. In my case, I wanted to create a project with multiple apps that I use in my Angular workshops. Having a single project with multiple apps allows you to run a time-consuming npm or yarn install once and just modify the name of the app you want to run.

For example, you may have multiple versions of the main bootstrap file that load different root modules. The file .angular-cli.json has the apps section with the property main, and to run a particular app, I’d instruct the students to modify .angular-cli.json to point at a particular app, e.g. "main": "main1.ts". To run another app, I’d instruct them to change this line to "main": "main2.ts".

But then I figured out that you can configure multiple apps in the same .angular-cli.json and run the build for a particular app by name. The apps property is an array, and you just need to configure each app there. For example, the following fragment shows how I configured two applications – app1 and app2 in the same .angular-cli.json:

"apps": [
    { "name":"app1",
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main-resolver.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css",
       "../node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    },
    { "name":"app2",
      "root": "src",
      "outDir": "dist2",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main-luxury.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css",
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],

Now to bootstrap the app main-resolver.ts I run the following command:

ng serve --app app1

To bootstrap the main-luxury.ts, I run this:

ng serve --app app2

You can also refer to each app by its index in the apps array:

ng serve --app 0
or
ng serve --app 1

The option –app is available for the ng build command as well. The following screen shot shows my project after I built the app1 into dist and app 2 into dist2.

This is a pretty useful Angular CLI feature and I wanted to share my findings with you.

Upgrading to the latest Angular CLI

As of the Angular CLI beta 30, the command to install Angular CLI looks as follows:

npm install -g @angular/cli

To get rid of the old version of Angular CLI and install the new one, run the following commands:

npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli

To update the existing CLI projects, modify the CLI dev dependency in package.json to this:

"@angular/cli": "1.0.0-beta.32"

Then update the CLI version on top of the angular-cli.json, remove your node_modules dir and run npm install.

My Angular 2 presentations for 2017

In 2017 I’m planning to speak at several conferences related to development of Web applications with the new Angular 2 framework. Below is the list of my presentations (each one is 90-min long). All of them can be delivered as a 2-day workshop in your organization.

Mastering TypeScript

TypeScript is a superset of JavaScript, which allows you to be more productive in writing JavaScript applications. The syntax of this language is pretty easy to pick up for anyone who’s familiar with such object-oriented languages as Java or C#. During this presentation you’ll learn the syntax of this language and will understand the benefits it brings to the table.

Make a facelift to your Angular 2 app with UI libraries

Commercial applications need to be good looking, which means that you should pick up a rich library of UI components for your app. While Angular Material library offers two dozen of great looking components, this may not be enough for your application needs. The good news is that there are other libraries that you can use. In this presentation we’ll start with an overview of Angular Material components. Then we’ll proceed with another open-source library called PrimeNG, which offers more than 70 UI components. Finally, we’ll review the code of an Angular 2 app that uses both Angular Material and PrimeNG components.

Angular 2 for Java developers

Angular 2 is a complete re-write of the super popular Web framework AngularJS. According to Pluralsight survey, Angular leads the list of what developers want to learn in 2016. Angular 2 is a component-based framework that will have an effect in JavaScript community similar to what Spring framework did for Java. This presentation is an overview of this hot framework, which in combination with TypeScript, finally made Web development understandable for Java developers. At the end of the presentation you’ll see a sample Web application written in Angular 2 on the front and Java on the server.

Angular 2: Working with the component router

In this session you’ll see how to use the router that comes with Angular 2 Final. We’ll start with configuring the navigation in a simple app. Then you’ll see how to pass data to routes, work child routes, and create apps with multiple router outlets (auxiliary routes). We’ll also review a unit-test configuration for testing router. Finally, you’ll see how how to lazy load modules using the router.

Angular 2: Communication with the server via HTTP and WebSocket protocols

In this session you’ll see how create an Angular 2 app that can communicate with the servers via a pull (HTTP) and push (WebSocket) modes. We’ll program a simple Node server and then will go through a number of code samples that communicate with it using HTTP and WebSocket protocols. We’ll start with creating a simple NodeJS server, and then will enable it to handle HTTP requests from an Angular 2 app. Then you’ll see how to wrap a service into an observable stream. Finally, we’ll teach our server to perform a data push to an Angular 2 client using the WebSocket protocol.

Implementing inter-component communication in Angular 2

Angular 2 is a component-based framework with a well-defined API for passing data to and getting data from a component. Any application is a tree of components that often need to communicate with each other.
In this presentation you’ll see how to create reusable application components that can exchange data with each other in a loosely-coupled manner. You’ll see how components can communicate via a common parent or via an injectable service. You’ll see how to pass data using component router, input and output parameters, events and callbacks. You’ll also learn how to use projection (formerly known as transclusion) to pass HTML fragments to a component’s template. We’ll also touch upon the incorporation of the third-party JavaScript libraries into an Angular 2 app.

Using Observable Streams in Angular 2

Angular 2 includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream.

Observables allow to introduce the push model to your application. First we’ll get familiar with the RxJS library, and then will continue reviewing observables in Angular 2. In this presentation you’ll see how to treat UI events, HTTP, and WebSocket connections as observable streams that push data. You’ll see how to wrap up any service into an observable stream so your application components can subscribe to it.

Angular 2 Tooling

Learning Angular 2 is easier than AngularJS, and developing in TypeScript is more productive than in JavaScript. But setting up the project and deploying the application is not straightforward. This presentation is not about the Angular 2 syntax. We’ll discuss the development process with Angular 2 starting from setting up the project to deploying an optimized application. We’ll start with discussing the Angular/TypeScript project structure and the proceed with such topics as using the module loader SystemJS, installing type definition files, bundling the app with Webpack and deployment in dev and prod. Finally, we’ll go through the process of scaffolding and bundling projects using the Angular CLI tool.

Angular CLI: Speed up installing dependencies with Yarn

Initially, the entry barrier into the world of Angular development was pretty high because of the need to learn and manually configure multiple tools. Even to get started with a simple application, you need to know and use the TypeScript language, the TypeScript compiler, ES6 modules, SystemJS, npm, and a development web server. To work on a real-world project, you also need to learn how to test and bundle your app.

To jumpstart the development process, the Angular team created a tool called Angular CLI (see https://github.com/angular/angular-cli), which is a command-line tool that covers all the stages of the Angular application lifecycle, from scaffolding and generating an initial app to generating boilerplate for your components, modules, services, and so on. The generated code also includes pre-configured files for unit tests and bundling with Webpack.

All this is good but a project generated by Angular CLI has a lot of dependencies that have to be downloaded and installed in the node_modules directory of your project. What’s “a lot”? Let’s use the Unix tree command to see how many files and directories exist in a project freshly generated by Angular CLI. Enter the following command in the root directory of such project:

tree node_modules

You’ll see a nicely formatted tree structure of all packages installed in the node_modules directory ai a summary line at the end, which will look like this:

6233 directories, 38656 files

This is what I mean by a lot. Actually all is relative. It clearly a lot if you compare with the content of node_modules of a jQuery project:

7 directories, 13 files

On the hand, the rumor has it that React Native installs 120K files. The software becomes more complicated every year and we have to deal with it. Anyway, Angular CLI has already created the project with all packages installed. Now, let’s delete the node_module dir in the project and reinstall it with npm install. On my laptop it takes at least 90 seconds. Can this time be improved? Yes, if you’ll use Yarn – an alternative to npm client.

Yarn is a new package manager that can be used instead of npm package manager. The plan is to use npm one last time to install Yarn, and then npm is not needed. Here’s the command to install Yarn globally:

npm install yarn -g

Now let’s run Yarn from within the root dir of our project:

yarn

This command reads (an equivalent of npm install) the list dependencies from your package.json file and installs all of them either from npmjs.org or from local cache. It takes anywhere from about one minute on the first run to install those 38K files. on the consecutive runs (after deleting node_modules) it takes 30 seconds. This is three times faster than npm! Pretty impressive.

To create a new Angular CLI project called sampleProj you can run the following command:

ng new sampleProj

The above command will generate the boilerplate code of the project in the directory sampleProj with package.json and will immediately run npm install there. On my MacBook Pro it takes at least 90 seconds. Now that we are fans of yarn, we’d like to integrate it in the initial project generation. This could be done in three steps:

1. Instruct Angular CLI to not run npm install:
ng new --skip-install sampleProj
2. cd sampleProj
3. yarn

If you use Mac or Unix-based OS, you can combine the above three steps as follows:

ng new --skip-install sampleProj && cd $_ && yarn

The bash parameter $_ refers to the last argument of the previous command, which is sampleProj in our case. Running the above command completes in 30 seconds, which is a lot better than 90, isn’t it?

For a regular non-CLI Angular project Yarn needs about 19 seconds on the first run and 12 seconds or less thereafter. On your computer, the results may be different.

Being more performant is not the only advantage of using Yarn over npm, and you can read more about Yarn’s architecture and benefits in Yarn blog. At the time of this writing, Yarn is still at its early stages, but you can start using it today.

UPDATE: As of Angular CLI Beta 31 you can simply set Yarn as your default package manager so Angular CLI will use it during generation of new projects:

ng set --global packageManager=yarn

I recorded the video showing how to do this.