Angular CLI — Setup, Verification, Routing and Testing by John Papa

Kevin O'Shaughnessy
12 min readJul 29, 2019

--

Welcome to this review of the Pluralsight course Angular CLI by John Papa. This course is the fourth course in the Angular learning path, after Angular: The Big Picture, Angular: Getting Started, and Angular Forms.

The Getting Started course has one short module on the Angular CLI, and this gives a useful overview of some of the tool’s main features. In this course we get an in-depth look at what this tool has to offer us.

John Papa is a Principal Developer Advocate with Microsoft and an alumni of the Google Developer Expert, Microsoft Regional Director, and MVP programs. He has produced many courses on front end development, including Play by Play: Insights from the Angular Team, Visual Studio Code, and Angular: First Look, which is a good option if you are totally new to Angular.

In the Insights from the Angular Team course, Stephen Fluin cites the CLI as one of the main innovations that distinguishes the new Angular from the original Angular JS.

As the name suggests, this course focuses on the Angular CLI tool and how to use it. CLI stands for Command Line Interface, and it helps us to produce Angular applications more quickly and to a high standard. John says it as “makes it easy to create an application that works and follows best practices, right out of the box.” If you are serious about web development using Angular, you will definitely want to learn this tool.

Motivation

John explains that there are a huge many of ways to create an app, and we should ask ourselves how can we be sure that we are following best practices and are writing testable and easy to maintain apps?

John Papa and Angular team lead Igor Minar have written a style guide, but not all developers have read it and follow it consistently. John says when the tooling handles the process, developers can focus on the users needs.

Sneak Peek

In this clip we see some common commands, along with shorthand versions to save you some typing.

You can also read up on these in the CLI Command Overview.

Test Driving the Angular CLI

We see that if we ever forget the syntax for a command, help is never far away. Just type:

ng —-help

And you will see a list of commands allow with their descriptions. We can also get help on a specific command, e.g.

ng serve --help

Running a linter is as simple as typing ng lint, and running unit test is as easy as typing ng test.

John has put up an Angular CLI demo on Github so that you can try out these commands for yourself.

Angular CLI Setup and Verification

Angular CLI Requirements

We should first check that we have the correct version of Node JS installed.

node -v

John says the Angular CLI currently supports Node version 8 or higher, so if the number is lower than this you’ll need to upgrade. To check the version of node package manager type:

npm -v

Any version from 5 and higher is needed for the Angular CLI. These numbers may change in the future so check out the quickstart guide if you are having any problems.

Installing and Verifying the Angular CLI

Once you’ve confirm you have a valid version of npm, type:

npm install -g @angular/cli

Once installed, type:

ng -v

This will report on the versions of the CLI tools that have just been installed. In this course John is running Angular CLI v6.0.8.

Generating and Exploring a New App

To quickly create an app called ngtest, type:

ng new ngtest —-skip-install

This creates about 20 or so files for us almost instantly. John shows us some of the files it has created for us.

Angular Extensions for VS Code

John Papa has written a popular extension pack for Visual Studio Code, called Angular Essentials, which contains 12 of John’s favorite extensions for Angular development. John says the most important of these extensions is the Angular Language Service.

In this clip we install this and see how much nicer VS Code looks with our demo Angular app. We can now run context sensitive npm commands via the GUI as a quick and easy alternative to typing out the commands.

Angular CLI resources

John Papa recommends the official Angular CLI site, the documentation site, and the GitHub page.

Generating a New Angular Application

Commands for Generating a New App

In this clip John explains the following commands:

ng new my-app
ng new my-app —-dry-run
ng new my-app —-skip-install

Generating and Customizing a New App

We start with a dry run, which shows us the files that it *would* create for us.

Then we see the — help results which shows us all of the latest commands that are supported. Most have single letter shortcuts which will save you time and typing, e.g. -d is short for — dry-run

The — skip-install flag is useful if you are working somewhere where you don’t have an internet connection, or if you’re just in a hurry.

Angular CLI JSON File

In this 11 minute clip, John takes us line by line through the generated angular.json file explaining the purpose of each setting.

We have one app defined in our “projects” object, which is named “my-app”.

The default prefix is “app”, e.g. this means we have app.component.ts and app.module.ts. We can change this if we want to, but “app” serves as a convenient convention. John shows us we can generate an app with a different prefix using — prefix, for example to generate an acme app:

ng new my-app2 —-prefix acme

The files are still generated with the same filenames app.module.ts and app.components.ts, but in the JSON file the prefix is “acme” and the main component selector is ‘acme-root’

Back in the JSON, we see the “architect” object is a big one, mainly because it contains a big object called “build”, which contains an “options” object with many different properties there.

We also learn that if we don’t want to bother writing unit tests we can use the — skip-tests flag with our CLI command. The shortcut for this is -S

To generate an app with the SASS styles instead of regular CSS, use the option:

—-style scss

If we use this option the generated angular.json has a “schematics” option with the property “styleext”: “scss”

The app generation does not generate any files for routing by default, but you can request these with the — routing flag

Common App Generation Flags

John begins by reviewing some of the flags used in the previous clip, then recommends combining options, for example:

ng new my-app —-routing —-prefix ma —-style scss —-dry-run

This clip feels a bit belabored after watching the previous clip, but we do cover something new which is using the open flag with the serve command:

ng serve -o

This opens up our browser and sets the URL to the correct localhost location for running our app.

Configuring the Angular CLI

This clip explains the ng config command.

For help on this command type ng config — help

Linting

Angular CLI makes it easy to lint our TypeScript code:

ng lint my-app

John covers a few different flag options for this command, and demonstrates them in VS Code by writing some sloppy TypeScript and showing what the linter picks up. The — format stylish flag makes the output much more readable:

ng lint my-app —-format stylish

We can even ask the linter to fix the problems for us:

ng lint my-app —-fix

Generating Code from Blueprints

Blueprints

Blueprints tell Angular how we want to create new files. The syntax is:

ng generate <blueprint><options>

Component Blueprints and Options

In this clip, John explains the flags:

— flat
— inline-template
— inline-style
— spec
— view-encapsulation
— change-detection
— dry-run

This all follows the same patterns that we’ve seen in the “Generating a New Angular Application” module.

The view encapsulation, and change detection flags add properties to the component directive that we are creating.

Declaring a Component in an NgModule

Here we see how to use VS Code’s git control to show changes. This shows us the differences between for and after we generate code with the Angular CLI.

In this module, John shows us examples of generating:

The above links take you to the relevant sections of the official documentation. As John says, you can always use the — help flag if you forget the syntax or otherwise need help quickly.

Generating Routing Features

In this module, as well as creating routes, we start to see how we can use all of the CLI generation features together when creating an app.

John creates a customer component and a dashboard component, and we use the Angular snippets extension to help us create routes to both of these, and also to create a default route.

John also demonstrates Emmet for creating html extra quickly.

Generating a new module with Routing

In John’s Angular: First Look course he takes us through his Azure Website For Showcasing Angular. In this clip we take another look at the Angular Routing Demo. We can route between characters and vehicles here. John gives us a quick look at the code and notes that although we have different components, all of the code is in the app main module.

We also see Angular: Eagerly Loaded Routes and look at the differences in the code between the two examples. We have a characters routing module in the second example. We see how we can build something like this with the aid of the Angular CLI.

Generating a Guard

To protect the routes we can generate a guard. This command generates an authorization guard.

ng g guard auth

Once generated we can add our authorization logic into it.

When we’ve developed our app we need to think about putting it into production. We’ll want to minify our code so that it runs as fast as possible.

Exploring a Development Build and Its Bundles

We continue with our simple angular routing app.

Using Chrome Devtools Network tab on our dev build, we see that vendor.js is a whopping 3.3MB in size.

John shows us npx webpack-bundle-analyzer which show’s us which JavaScript files are the big ones, and which ones are smaller.

Building Target and Environments

In this clip John runs through all the differences between the regular ng build command and the ng build — prod command.

We always want to use the — prod flag before deploying into production.

Production Builds

We can use Ahead of Time compilation:

ng build —-aot —-stats-jsonnpm run stats

In this clip we see how much the file sizes have reduced by the AOT compilation process. It’s a significant reduction but the biggest reduction comes from using the — prod flag.

You can get the full list of flag descriptions for build using help:

ng build -h

Serving Angular

John runs through the main flags that are used with ng serve.

You can get a list of these by doing ng serve — help or by reviewing the official ng serve docs.

Exploring Angular Serving Options

In this clip we see how to turn on live-reload, a useful feature that automatically runs our latest code without us needing to manually reload the page in the browser.

Adding New Capabilities

The Angular CLI also let’s us add new packages, such as @angular/pwa or @angular/material.

Adding Angular Material

The CLI takes care of a lot of the plumbing for us.

When we adding Angular Material, a whole bunch of new modules and components are imported in our app.module.ts file.

John demonstrates how to reorganize the code to take advantage of the new Angular Material features. When we serve up the app, we see it looks a lot different than before. Next we use the CLI to create a dashboard component:

ng g @angular/material:material-dashboard —-name dashboard

Or how about adding a table?

ng g @angular/material:material-table —-name customer-list

Running Unit and End to End Tests

Testing Angular

Google have created two tools for testing your Angular apps:

  • Karma, for doing unit tests
  • Protractor, for doing end to end tests

To find all the testing options you have with the Angular CLI type:

ng test —-help

When we execute ng test it will find all *.spec.ts files that we have in our workspace (which can include multiple projects) and run them all.

Executing Unit Tests

John runs the tests that the CLI auto-generated and finds 8 of them are failing. He explains the errors and shows how to fix them. Many of the failures are due to missing imports for Angular Material modules.

CLI Testing Options

John describes some of the different flag options, and then talks about the differences between a single test cycle, and continuous testing.

Code Coverage

Using the code coverage flag we can see how much of our code is covered by unit tests:

ng test —-code-coverage

A new directory called coverage is created and this contains CSS, HTML and JavaScript files. By opening up the index.html file we see the results open in a browser and are nicely styled for us.

John shows us that we can drill into the results and see each line of code this is and isn’t covered by tests. Even which statements in a single line are covered. Very useful!

Debugging Unit Tests

There’s a DEBUG button in the karma results window. If we click this we can open up the devtools and set breakpoints in our JavaScript.

This helps us to understand why our tests are passing or failing.

End to End Tests

End to end testing is testing the application behavior through user navigation. To get help on running end to end tests using the CLI, type:

ng e2e —-help

Or just give it a try using ng e2e

Executing End to End Tests

Here we begin with a look at the protractor.conf.js file. Most of the config is the exports.config definition, which set properties such as allScriptsTimeout, specs, capabilities and framework.

Then John takes us through app.e2e.spec.ts, and runs ng e2e

This is really just a quick introduction to end to end testing. Pluralsight has other courses that cover the topic in more depth.

Tooling Features

Updating Angular

John explains that keeping Angular up to date is important for maintainability, performance and security.

In the early days of Angular Alpha and Beta, updating your app was sometimes hard work. Today with the Angular CLI, we have a simple command to do the heavy lifting for us: ng update

This command also updates 3rd party libraries and schematics.

The most common flags with ng update are:

—-dry-run
--all
--force

Running ng update

John Papa recommends you check out update.angular.io

This guide is from the Angular Team and gives you advice on how to upgrade as painlessly as possible.

In this clip John shows us how to upgrade from Angular 5.2 to Angular 6.0. Most of the steps are also applicable for upgrading to later versions.

We see the package.json file before and after side by side, and John notes all the dependency versions that are updated. The CLI is one of the dependencies due to be upgraded by itself. Even TypeScript is upgraded.

John explains why you may need to run the update twice to fix your angular.json file.

Updating our demo

We run ng update and we see the CLI informs us the packages cli, core, and material need updating. John shows us that we can elect to update these one at a time:

ng update @angular/cli
ng update @angular/core
ng update @angular/material

Multiple Projects

The Angular CLI supports workspaces containing multiple projects, and this is represented in the angular.json file.

By default we execute commands against ALL projects in a workspace, but we can target individual projects if we want to.

Workspaces

John reminds us that we can generate new applications with the CLI, and we use this to create a 2nd project in our workspace.

Then we look at the angular.json file and see the new project is defined within the projects object. There’s also a projects directory containing both projects. We also see how to build a specific project.

Generating Libraries

To generate a new library we can run:

ng generate library <name_of_your_library> <options>

We also see that we can publish our libraries to npm. To learn about npm publishing see John Papa’s page, Contributing packages to the registry.

Creating a Logger Library

In this clip we generate a library and update it to contain a logging service.

In app.component.ts we want to use this library, and we have to build it before it can find it. We also need to export our logger service from public_api.ts.

Angular Console

The Angular Console is a UI written using Electron that can do everything that the CLI does, and also adds some new features.

It’s been created by Narwhal Technologies in collaboration with the Angular team.

In this clip, John gives us a quick demo of what it can do.

Many thanks to John Papa and the Pluralsight team for producing this course.

Please follow me for more reviews of Pluralsight courses on the Angular learning path.

--

--

Kevin O'Shaughnessy

Sr. Full Stack Web Dev promoting better professional practices, tools, solutions & helping others.