JavaScript
Article
By Jurgen Van de Moere

The Ultimate Angular CLI Reference Guide

By Jurgen Van de Moere

Build an Angular CRUD App from the Ground Up

The Ultimate Angular CLI Reference Guide was peer reviewed by Tim Severien, Vildan Softic and Joan Yin. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

A large, bible-like Angular CLI reference book on a stand


2017.02.17: As of February 9, 2017, the ng deploy command has been removed from the core of Angular CLI. Read more here.


This is the preliminary article in a 4-part series on how to write a Todo application in Angular 2.

  1. Part 0— The Ultimate Angular CLI Reference Guide
  2. Part 1— Getting our first version of the Todo application up and running
  3. Part 2— Creating separate components to display a list of todo’s and a single todo
  4. Part 3— Update the Todo service to communicate with a REST API
  5. Part 4— Use Component Router to route to different components

On September 15, 2016, Angular 2 Final was released.

Where Angular 1.x was limited to a framework, Angular 2 has grown into an ambitious platform that allows you to develop fast and scalable applications across all platforms such as web, mobile web, native mobile and even native desktop.

With this transition to a platform, tooling has become more important than ever. However, setting up and configuring tooling is not always easy. To make sure Angular developers can focus on building applications with as little friction as possible, the Angular team is putting a lot of effort in providing developers with a high quality development toolset.

Part of that toolset are close integrations with a wide array of IDE’s and editors. Another part of that toolset is Angular CLI.

In this article we have a look at what Angular CLI is, what it can do for you, and how it performs some of its magic behind the scenes. Even if you already use Angular CLI, this article can serve as a reference to better understand its inner workings.

Technically you are not required to use Angular CLI to develop an Angular 2 application, but its many features can highly improve the quality of your code and save you a lot of time along the way.

So let’s get started!

What Is Angular CLI?

Angular CLI is a Command Line Interface (CLI) to automate your development workflow. It allows you to:

  • create a new Angular application
  • run a development server with LiveReload support to preview your application during development
  • add features to your existing Angular application
  • run your application’s unit tests
  • run your application’s end-to-end (E2E) tests
  • build your application for deployment to production
  • deploy your application to a server

Before we have a look at each of the above in detail, let’s first see how you can install Angular CLI.

Prerequisites

Before you can use Angular CLI, you must have Node.js 4.0.0 and npm 3.0.0 or higher installed on your system.

You can download the latest version of Node.js for your Operating System and consult the latest installation instructions on the official Node.js website.

If you already have Node.js and npm installed, you can verify their version by running:

$ node -v # => displays your Node.js version 
$ npm -v # => displays your npm version

Once you have Node.js installed, you can use the npm command to install TypeScript:

$ npm install -g typescript@2.0.2

Although TypeScript is technically not an absolute requirement, it is highly recommended by the Angular team, so I recommend you install it to make working with Angular 2 as comfortable as possible.

Now that you have Node.js and TypeScript installed, you can install Angular CLI.

Installing Angular CLI

To install Angular CLI, run:

$ npm install -g angular-cli

which will install the ng command globally on your system.

To verify whether your installation completed successfully, you can run:

$ ng version

which displays the version you have installed:

angular-cli: 1.0.0-beta.17
node: 6.1.0
os: darwin x64

Depending on your system setup, you may see the following warning in Angular CLI’s output:

Could not start watchman; falling back to NodeWatcher for file system events.
Visit http://ember-cli.com/user-guide/#watchman for more info.

This warning tells you two things:

  1. Angular CLI is based on Ember CLI, the CLI of the Ember framework.
  2. Watchman is not installed on your system

Watchman

Watchman is a scalable file watching service built by the Facebook Engineering team that offers better performance than similar services.

Angular CLI will fall back to NodeWatcher if you don’t have Watchman installed.

However, you may benefit from improved performance if you install Watchman, so it’s definitely worth checking out the installation instructions to see if Watchman supports your operating system.

If you are running Mac OS X, you can install Watchman using Homebrew:

$ brew install watchman

Now that you have Angular CLI installed, let’s use it to create a new application.

Creating a New Angular Application

There are two ways to create a new application using Angular CLI:

  • ng init: create a new application in the current directory
  • ng new: create a new directory and run ng init inside the new directory

So ng new is similar to ng init except that it also creates a directory for you.

Assuming you haven’t created a directory yet, let’s use ng new to create a new project:

$ ng new my-app

Behind the scenes, the following happens:

  • a new directory my-app is created
  • all source files and directories for your new Angular application are created based on the name you specified (my-app) and best-practices from the official Angular Style Guide
  • npm dependencies are installed
  • TypeScript is configured for you
  • the Karma unit test runner is configured for you
  • the Protractor end-to-end test framework is configured for you
  • environment files with default settings are created

You will learn more about each of these aspects in the following sections.

At this point you have a working Angular application and your new directory my-app looks like this:

my-app
├── README.md
├── angular-cli.json
├── e2e
│   ├── app.e2e-spec.ts
│   ├── app.po.ts
│   └── tsconfig.json
├── karma.conf.js
├── package.json
├── protractor.conf.js
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   ├── app.module.ts
│   │   ├── index.ts
│   │   └── shared
│   │       └── index.ts
│   ├── assets
│   ├── environments
│   │   ├── environment.prod.ts
│   │   └── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   ├── test.ts
│   ├── tsconfig.json
│   └── typings.d.ts
└── tslint.json

Available Options

  • --dry-run: boolean, default false, perform dry-run so no changes are written to filesystem
  • --verbose: boolean, default false
  • --link-cli: boolean, default false, automatically link the angular-cli package (more info)
  • --skip-npm: boolean, default false, skip npm install
  • --skip-bower: boolean, default true, skip bower install
  • --skip-git: boolean, default false, don’t initialize Git repository
  • --directory: string, name of directory to create, by default this is the same as the application name
  • --source-dir: string, default 'src', name of source directory
  • --style: string, default 'css', the style language to use ('css', 'less' or 'scss')
  • --prefix: string, default 'app', the prefix to use when generating new components
  • --mobile: boolean, default false, generate a Progressive Web App application (see section on upcoming features)
  • --routing: boolean, default false, add module with routing information and import it in main app module
  • --inline-style: boolean, default false, use inline styles when generating the new application
  • --inline-template: boolean, default false, use inline templates when generating the new application

Let’s see how you can start your application so you can see it in action.

Running Your Application

To preview your new application in your browser, navigate to its directory:

$ cd my-app

and run:

$ ng serve

to start the built-in development server on port 4200:

** NG Live Development Server is running on http://localhost:4200. **
3935ms building modules
Hash: fd7ad6cf3503757e22e0
Version: webpack 2.1.0-beta.25
Time: 6526ms
            Asset       Size  Chunks             Chunk Names
   main.bundle.js    2.78 MB    0, 2  [emitted]  main
 styles.bundle.js    10.2 kB    1, 2  [emitted]  styles
        inline.js    5.53 kB       2  [emitted]  inline
         main.map    2.86 MB    0, 2  [emitted]  main
       styles.map    14.1 kB    1, 2  [emitted]  styles
       inline.map    5.59 kB       2  [emitted]  inline
       index.html  472 bytes          [emitted]
assets/.npmignore    0 bytes          [emitted]
Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks       Chunk Names
    index.html  2.81 kB       0
webpack: bundle is now VALID.

You can now navigate your favorite browser to http://localhost:4200/ to see your application in action:

Screenshot of the app running in the browser, displaying the text 'app works!'

Behind the scenes, the following happens:

  1. Angular CLI loads its configuration from angular-cli.json
  2. Angular CLI runs Webpack to build and bundle all JavaScript and CSS code
  3. Angular CLI starts webpack dev server to preview the result on localhost:4200

Notice that the ng serve command does not exit and return to your terminal prompt after step 3.

Instead, because it includes LiveReload support, the process actively watches your src directory for file changes. When a file change is detected, step 2 is repeated and a notification is sent to your browser so it can refresh automatically.

To stop the process and return to your prompt, press ctrl-c.

Adding Features to Your Angular Application

You can use the ng generate command to add features to your existing application:

  • ng generate class my-new-class: add a class to your application
  • ng generate component my-new-component: add a component to your application
  • ng generate directive my-new-directive: add a directive to your application
  • ng generate enum my-new-enum: add an enum to your application
  • ng generate module my-new-module: add a module to your application
  • ng generate pipe my-new-pipe: add a pipe to your application
  • ng generate service my-new-service: add a service to your application

The generate command and the different sub-commands also have shortcut notations, so the following commands are similar:

  • ng g cl my-new-class: add a class to your application
  • ng g c my-new-component: add a component to your application
  • ng g d my-new-directive: add a directive to your application
  • ng g e my-new-enum: add an enum to your application
  • ng g m my-new-module: add a module to your application
  • ng g p my-new-pipe: add a pipe to your application
  • ng g s my-new-service: add a service to your application

Each of the different sub-commands performs a different task and offers different options and parameters.

Let’s have a look at each of them.

Adding a new class

To add a class called UserProfile, run:

$ ng generate class user-profile
installing component
  create src/app/user-profile.ts

Angular CLI will automatically adjust the letter case of the file name and class name for you, so the following commands have the same effect:

# All three commands are equivalent
$ ng generate class user-profile
$ ng generate class userProfile
$ ng generate class UserProfile

Behind the scenes, the following happens:

  • a file src/app/user-profile.ts is created that exports an empty class named UserProfile

Available options

  • --spec: boolean, default false, generate spec file with unit test

Examples:

# Generate class 'UserProfile'
$ ng generate class user-profile

# Generate class 'UserProfile' with unit test
$ ng generate class user-profile --spec

Adding a new component

To add a component with a selector app-site-header, run:

$ ng generate component site-header
installing component
  create src/app/site-header/site-header.component.css
  create src/app/site-header/site-header.component.html
  create src/app/site-header/site-header.component.spec.ts
  create src/app/site-header/site-header.component.ts

Angular CLI will automatically adjust the letter case of the file name and component name for you and apply the prefix to the component selector, so the following commands have the same effect:

# All three commands are equivalent
$ ng generate component site-header
$ ng generate component siteHeader
$ ng generate component SiteHeader

Behind the scenes, the following happens:

  • a directory src/app/site-header is created
  • inside that directory 4 files are generated:
    • a CSS file for the component styles
    • an HTML file for the component template
    • a TypeScript file with a component class named SiteHeaderComponent and selector app-site-header
    • a spec file with a sample unit test for your new component
  • SiteHeaderComponent is added as a declaration in the @NgModule decorator of the nearest module, in this case the AppModule in src/app/app.module.ts

Available options

  • --flat: boolean, default false, generate component files in src/app instead of src/app/site-header
  • --inline-template: boolean, default false, use an inline template instead of a separate HTML file
  • --inline-style: boolean, default false, use inline styles instead of a separate CSS file
  • --prefix: boolean, default true, use prefix specified in angular-cli.json in component selector
  • --spec: boolean, default true, generate spec file with unit test

Examples:

# Generate component 'site-header'
$ ng generate component site-header

# Generate component 'site-header' with inline template and inline styles
$ ng generate component site-header --inline-template --inline-style

Adding a new directive

To add a directive with a selector appAdminLink, run:

$ ng generate directive admin-link
installing directive
  create src/app/admin-link.directive.spec.ts
  create src/app/admin-link.directive.ts

Angular CLI will automatically adjust the letter case of the file name and directive name for you and apply the prefix to the directive selector, so the following commands have the same effect:

# All three commands are equivalent
$ ng generate directive admin-link
$ ng generate directive adminLink
$ ng generate directive AdminLink

Behind the scenes, the following happens:

  • a file src/app/admin-link.directive.ts is created that exports a directive named AdminLinkDirective with a selector appAdminLink
  • a file src/app/admin-link.directive.spec.ts is created with a unit test for the directive

Available options

  • --flat: boolean, default true, generate directive files in src/app instead of src/app/admin-link
  • --prefix: boolean, default true, use prefix specified in angular-cli.json in directive selector
  • --spec: boolean, default true, generate spec file with unit test

Examples:

# Generate directive 'adminLink'
$ ng generate directive admin-link

# Generate directive 'adminLink' without unit test
$ ng generate directive admin-link --spec=false

Adding a new enum

To add an enum called Direction, run:

$ ng generate enum direction
installing enum
  create src/app/direction.enum.ts

Angular CLI will automatically adjust the letter case of the file name and enum name for you, so the following commands have the same effect:

# Both commands are equivalent
$ ng generate enum direction
$ ng generate enum Direction

Behind the scenes, the following happens:

  • a file src/app/direction.enum.ts is created that exports an enum named Direction

Available options

There are no command line options available for this command.

Adding a new module

To add a new module to your application, run:

$ ng generate module admin
installing module
  create src/app/admin/admin.module.ts
installing component
  create src/app/admin/admin.component.css
  create src/app/admin/admin.component.html
  create src/app/admin/admin.component.spec.ts
  create src/app/admin/admin.component.ts

Behind the scenes, the following happens:

  • a directory src/app/admin is created
  • an AdminModule module is created inside src/app/admin/admin.module.ts
  • a component AdminComponent is created in src/app/admin:
    • a CSS file is created for the component styles
    • an HTML file is created for the component template
    • a TypeScript file is created with a component class named AdminComponent and selector app-admin
    • a spec file with a sample unit test for the new AdminComponent component
  • AdminComponent is added as a declaration in the @NgModule decorator of the AdminModule in src/admin/admin.module.ts

Notice that the AdminModule module is not added automatically to your main module AppModule in src/app/app.module.ts. It is up to you to import the module where you need it.

To import your new module in another module, you can specify is as an import in an @NgModule definition. For example:

import { AdminModule } from './admin/admin.module';

@NgModule({
  // ...
  imports: [
    AdminModule
  ]
})
export class AppModule { }

Available options

  • --routing: boolean, default false, generate an additional module AdminRoutingModule with just the routing information and add it as an import to your new module
  • --spec: boolean, default false, add src/app/admin/admin.module.spec.ts with a unit test that checks whether the module exists

Examples:

# Add module 'admin'
$ ng generate module admin

# Add module 'admin' with additional module containing routing information
$ ng generate module admin --routing

Adding a new pipe

A pipe is the Angular 2 equivalent of a filter in AngularJS 1.x and allows you to transform a displayed value within a template.

To add a pipe with a name convertToEuro, run:

$ ng generate pipe convert-to-euro
installing pipe
  create src/app/convert-to-euro.pipe.spec.ts
  create src/app/convert-to-euro.pipe.ts

Angular CLI will automatically adjust the letter case of the file name and pipe name for you, so the following commands have the same effect:

# All three commands are equivalent
$ ng generate pipe convert-to-euro
$ ng generate pipe convertToEuro
$ ng generate pipe ConvertToEuro

Behind the scenes, the following happens:

  • a file src/app/convert-to-euro.pipe.ts is created that exports a pipe class named ConvertToEuroPipe
  • ConvertToEuroPipe is added as a declaration in the @NgModule decorator of the nearest module, in this case the AppModule in src/app/app.module.ts

Available options

  • --flat: boolean, default true, generate component files in src/app instead of src/app/site-header
  • --spec: boolean, default true, generate spec file with unit test

Examples:

# Generate pipe 'convertToEuro' with spec and in /src/app directory
$ ng generate pipe convert-to-euro

# Generate pipe 'convertToEuro' without spec and in /src/app/convert-to-euro directory
$ ng generate pipe convert-to-euro --spec=false --flat=false

Adding a new service

To add a service with a dependency injection token BackendApiService, run:

$ ng generate service backend-api
installing service
  create src/app/backend-api.service.spec.ts
  create src/app/backend-api.service.ts
  WARNING Service is generated but not provided, it must be provided to be used

Angular CLI will automatically adjust the letter case of the file name and pipe name for you, so the following commands have the same effect:

# All three commands are equivalent
$ ng generate service backend-api
$ ng generate service backendApi
$ ng generate service BackendApi

Behind the scenes, the following happens:

  • a file src/app/backend-api.service.ts is created that exports a service class named BackendApiService
  • a file src/app/backend-api.service.spec.ts is created with a unit test for your new service

Notice how Angular CLI warns that the service is generated but not provided anywhere yet. It is up to you to register the service as a provider by adding it to the providers: [] array where you need it (e.g. in a module or component). For example:

import { BackendApiService } from './backend-api.service';

@NgModule({
  // ...
  providers: [BackendApiService],
  bootstrap: [AppComponent]
})

Available options

  • --flat: boolean, default true, generate service file in src/app instead of src/app/backend-api
  • --spec: boolean, default true, generate spec file with unit test

Examples:

# Generate service with DI token 'BackendApiService' in /src/app directory
$ ng generate service backend-api

# Generate service with DI token 'BackendApiService' in /src/app/backend-api directory
$ ng generate service backend-api --flat=false

Special note

Angular CLI does not just blindly generate code for you. It uses static analysis to better understand the semantics of your application.

For example, when adding a new component using ng generate component, Angular CLI finds the closest module in the module tree of your application and integrates the new feature in that module.

So if you have an application with multiple modules, Angular CLI will automatically integrate the new feature in the correct module, depending on the directory where you run the command from.

Running Your Unit Tests

Angular CLI automatically configures the Karma test runner for you when your application is initially created.

When adding a feature to your application, you can use the --spec option to specify whether you want Angular CLI to also create a corresponding .spec.ts file with a sample unit test for your new feature.

Spec files are created in the same directory of their corresponding feature in the src directory. This allows you to easily locate them when working on a feature.

Running all unit tests of your application thus implies running all unit tests specified in all files ending in .spec.ts in all directories inside your src directory.

To run all unit tests, run:

$ ng test

The following output will appear in your console:

[karma]: No captured browser, open http://localhost:9876/
[karma]: Karma v1.2.0 server started at http://localhost:9876/
[launcher]: Launching browser Chrome with unlimited concurrency
[launcher]: Starting browser Chrome
[Chrome 53.0.2785 (Mac OS X 10.12.0)]: Connected on socket /#9KHc7IVVulsBRJWgAAAA with id 95795517
Chrome 53.0.2785 (Mac OS X 10.12.0): Executed 6 of 6 SUCCESS (0.151 secs / 0.141 secs)

and a special browser instance will be launched:

Browser window showing the Karma test runner screen

Here is what happens behind the scenes:

  1. Angular CLI loads angular-cli.json.
  2. Angular CLI runs Karma with the configuration specified in angular-cli.json. By default this is karma.conf.js located in the root directory of your application.
  3. Karma opens the browser specified in the Karma configuration. By default the browser is set to Google Chrome.
  4. Karma then instructs the browser (Chrome) to run src/test.ts using the testing framework specified in the Karma config. By default this is the Jasmine framework. The file src/test.ts is automatically created when your application is created. It is pre-configured to load and configure the code that is needed to test your Angular application and run all spec files ending in .spec.ts in your src directory.
  5. Karma reports the result of the test run to the console.
  6. Karma watches the src file for changes and repeats step 4 and 5 when a file change is detected.

To end the process, you can press ctrl-c.

If you want to learn more about testing your Angular code, you can check out the Official Angular Testing Guide.

Running Your End-to-end (E2E) Tests

Angular CLI automatically configures Protractor for you when your application is initially created.

To run your E2E tests, run:

$ ng e2e

The following output will appear in your console:

[10:26:12] I/direct - Using ChromeDriver directly...
[10:26:12] I/launcher - Running 1 instances of WebDriver
Started
Spec started
.
  my-app App
    ✓ should display message saying app works
1 spec, 0 failures
Finished in 0.55 seconds
Executed 1 of 1 spec SUCCESS in 0.551 sec.
[10:26:13] I/launcher - 0 instance(s) of WebDriver still running
[10:26:13] I/launcher - chrome #01 passed

All end-to-end tests pass.

and a special browser instance will be launched:

Browser window showing 'app works!' text

Here is what happens behind the scenes:

  1. Angular CLI loads angular-cli.json.
  2. Angular CLI runs Protractor with the configuration specified in angular-cli.json. By default this is the protractor.conf.js file located in the root directory of your application.
  3. Protractor opens the browser specified in the Protractor configuration. By default the browser is set to Google Chrome.
  4. Protractor then instructs the browser (Chrome) to run all spec files ending in .e2e-spec.ts in your e2e directory.
  5. Protractor reports the result of the test run to the console.

To process then exits automatically after step 5.

If you want to learn more about E2E testing your Angular code, you can check out the Official Angular Testing Guide and the Protractor documentation.

Building Your Application for Production

Running ng serve builds and bundles your Angular application automatically to a virtual filesystem during development.

However, when your application is ready for production, you will need real files that you can deploy to your server or to the cloud.

To build and bundle your application for deployment, run:

$ ng build

The output of the command is sent to your console:

3656ms building modules
Hash: 69fb9d88c4f502e01790                                                                                                                                                  
Version: webpack 2.1.0-beta.25
Time: 6457ms
            Asset       Size  Chunks             Chunk Names
   main.bundle.js    2.54 MB    0, 2  [emitted]  main
 styles.bundle.js    10.2 kB    1, 2  [emitted]  styles
        inline.js    5.53 kB       2  [emitted]  inline
         main.map    2.57 MB    0, 2  [emitted]  main
       styles.map    14.1 kB    1, 2  [emitted]  styles
       inline.map    5.59 kB       2  [emitted]  inline
       index.html  472 bytes          [emitted]  
assets/.npmignore    0 bytes          [emitted]  
chunk    {0} main.bundle.js, main.map (main) 2.03 MB {1} [initial] [rendered]
chunk    {1} styles.bundle.js, styles.map (styles) 9.96 kB {2} [initial] [rendered]
chunk    {2} inline.js, inline.map (inline) 0 bytes [entry] [rendered]
Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks       Chunk Names
    index.html  2.81 kB       0       
    chunk    {0} index.html 339 bytes [entry] [rendered]

What happens behind the scenes is:

  1. Angular CLI loads its configuration from angular-cli.json
  2. Angular CLI runs Webpack to build and bundle all JavaScript and CSS code
  3. The result is written to the outDir directory specified in your Angular CLI configuration. By default, this is the dist directory.

Available options

  • --aot: enable ahead-of-time compilation (see section on future features)
  • --base-href: string, the base href to use in the index file
  • --environment: string, default dev, environment to use
  • --output-path: string, directory to write the output to
  • --target: string, default development, environment to use
  • --watch: boolean, default false, watch files for changes and rebuild when a change is detected

Targets

Specifying a target impacts the way the build process operates. Its value can be one of the following:

  • development: default mode, do not minify or uglify code
  • production: minify and uglify code

Building your application in production mode:

$ ng build --target=production

results in bundles that are minified, uglified and have hashes in their names:

3596ms building modules
Hash: 3d5ff21d335b08426087                                                                                                                                                  
Version: webpack 2.1.0-beta.25
Time: 9643ms
                                 Asset       Size  Chunks             Chunk Names
   main.a8db3859286ec456f5d8.bundle.js     825 kB    0, 2  [emitted]  main
 styles.b52d2076048963e7cbfd.bundle.js    3.97 kB    1, 2  [emitted]  styles
                             inline.js    1.39 kB       2  [emitted]  inline
main.a8db3859286ec456f5d8.bundle.js.gz     187 kB          [emitted]  
                            index.html  514 bytes          [emitted]  
                     assets/.npmignore    0 bytes          [emitted]  
chunk    {0} main.a8db3859286ec456f5d8.bundle.js (main) 2.03 MB {1} [initial] [rendered]
chunk    {1} styles.b52d2076048963e7cbfd.bundle.js (styles) 9.96 kB {2} [initial] [rendered]
chunk    {2} inline.js (inline) 0 bytes [entry] [rendered]

Environments

Environments let you specify settings to customize your application behavior.

You can define your own environments in the angular-cli.json file. The default ones are:

  • source: use settings defined in environments/environment.ts
  • dev: use settings defined in environments/environment.ts
  • prod: use settings defined in environments/environment.prod.ts

where environments/environment.ts equals:

export const environment = {
  production: false
};

and environments/environment.prod.ts equals:

export const environment = {
  production: true
};

The build process will use the dev environment by default.

If you specify a different environment, the build process will use the corresponding environment:

# Uses environments/environment.ts
$ ng build

# Also uses environments/environment.ts
$ ng build --environment=dev

# Uses environments/environment.prod.ts
$ ng build --environment=prod

As you can see in src/main.ts, you can access the environment settings from your code by importing environments/environment:

import './polyfills.ts';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

The build process will make sure the right environment is provided when you import it.

Deploying Your Application

When your application is ready for deployment, you can use Angular CLI to deploy your application to a hosting provider.

Currently Angular CLI only includes support for GitHub Pages:

$ ng github-pages:deploy

Behind the scenes, the following happens:

  1. Your application is built and bundled in production mode (production target + production environment)
  2. The result is written to the dist directory
  3. A gh-pages branch is created in your Git repository with the appropriate files and layout that GitHub expects
  4. A Git commit is created
  5. The commit is pushed to GitHub

If there is no GitHub remote defined in your Git repository, Angular CLI will prompt you for the necessary details.

Available options

  • --message: string, commit message to use with the build, must be wrapped in quotes
  • --target: string, default development, environment to use
  • --environment: string, default dev, environment to use
  • --user-page: boolean, default false, deploy as user/org page on GitHub
  • --skip-build: boolean, default false, skip building the application before deployment
  • --gh-token: string, GitHub token to use
  • --gh-username: string, GitHub username to use
  • --base-href: string, the base href to use in the index file

Support for other hosting providers will be added in the future.

A Glimpse into the Future

Angular CLI’s roadmap contains many exciting upcoming features:

  • Ahead-of-Time (AOT) Compilation Support
    Enabling AOT compilation will allow you to radically improve your application performance by compiling components and templates during the build process.
    Learn more about AOT here.
  • Progressive Web App (PWA) Support
    Angular CLI will be able to create a Web Application Manifest for you, generate an App Shell and provide Service Worker scripts to cache your application data.
    Learn more about mobile support here.
  • Refactoring Support
    In addition to adding features to your application, Angular CLI will also let you refactor existing features, for example, moving a component or renaming a service.
  • Upgrade Support
    Angular CLI will be able to help you with Angular upgrades. Because Angular CLI has a semantic understanding of your application, it will be able to help you with code changes that are required when upgrading to a newer version of Angular.
  • Extensibility
    Improved extensibility support so you can create your own custom add-ons and deployment scripts.
  • Increased Performance
    Improved performance so Angular CLI becomes faster.
  • Library Developer Mode
    In addition to creating a new application, Angular CLI will also let you create a new library that can be consumed by others.

Some of these features are already partially available. Check out the GitHub repository if you want to play around with them.

Summary

Angular CLI is a Command Line Interface (CLI) to automate your development workflow.

Today, you can already use Angular CLI to:

  • create a new Angular application
  • run a development server with LiveReload support to preview your application during development
  • add features to your existing Angular application
  • run your application’s unit tests
  • run your application’s end-to-end (E2E) tests
  • build your application for deployment to production
  • deploy your application to a server

Although it is technically not required to use Angular CLI to develop an Angular application, it can definitely improve the quality of your code and save you a lot of time and effort.

Because of the many exciting features that will be added over time, Angular CLI will probably become an indispensable tool for developing Angular applications.

To learn more about Angular CLI, check out the official website and the GitHub repository.

  • Great article and nice tip about watchman thanks

    • jvandemo

      Thank you @DuncanHunter:disqus, much appreciated!

  • Jithu Reddy

    Hai

    Thank you, It was Good article and very helpful. I’m trying to run my-app project it’s getting error in command prompt . how do i solve this error. Is there any solution for this error.

    Error:

    6557ms building modules 3ms add11134ms 109ms asset34ms emittingevents.js:160
    throw er; // Unhandled ‘error’ event
    ^

    Error: This socket is closed
    at WriteStream.Socket._writeGeneric (net.js:683:19)
    at WriteStream.Socket._write (net.js:734:8)
    at doWrite (_stream_writable.js:334:12)
    at writeOrBuffer (_stream_writable.js:320:5)
    at WriteStream.Writable.write (_stream_writable.js:247:11)
    at WriteStream.Socket.write (net.js:661:40)
    at WriteStream.process.stderr.write (C:projectsmy-appnode_modulesangular-clilibcliindex.js:40:27)
    at Console.warn (console.js:51:16)
    at printErrorAndExit (C:projectsmy-appnode_modulesangular-clinode_modulessource-map-supportsource-map-support.js:406:11)
    at process.emit (C:projectsmy-appnode_modulesangular-clinode_modulessource-map-supportsource-map-support.js:419:16)
    at process._fatalException (bootstrap_node.js:292:26)

    • jvandemo

      Hi @jithureddy:disqus, what command are your running when you get the error? Thank you!

      • Jithu Reddy

        ng serve command to run application

        • jvandemo

          @jithureddy:disqus Can you put your code in a Git repository? I can try and reproduce it here if you like. Thank you!

          • Jithu Reddy

            i didn’t write any new code in that project. i just installed angular-cli and created a new project same as you mention in the article and tried to run created project. using ng serve

          • jvandemo

            There seems to be an issue on this in the Angular CLI repository: https://github.com/angular/angular-cli/issues/3102. It may be related to an underlying issue with node (https://github.com/nodejs/node/issues/9542) and using Node v6.9.1 seems to solve the issue. Can you try that? Thanks!

          • Jithu Reddy

            i’m using node v7.0.

          • Jithu Reddy

            It’s running. Thank you very much.
            could you tell me how to install watchman in windows 10 OS.

          • jvandemo

            The official Watchman installation instructions can be found here: https://facebook.github.io/watchman/docs/install.html. I am not sure if the Watchman team is going to officially support Windows. You can follow this thread for more updates: https://github.com/facebook/watchman/issues/19. Hope that helps!

          • Jithu Reddy

            Thank you very much.

          • jvandemo

            My pleasure – thank you for your feedback!

          • Jithu Reddy

            I have one more question.

          • Jithu Reddy

            Hai@jvandemo

            When i create a new directory using ng new command one source file is missing in the created directory.

          • jvandemo

            Hi @jithureddy:disqus – What file exactly is missing? The entire src/app directory? Can you do `ng new your-app` and then `ng serve` when it generated the files and installed dependencies? Thanks!

          • Jithu Reddy

            shared/index.ts file missing in src/app/——

          • jvandemo

            @jithureddy:disqus – If something goes wrong when running `ng new`, then I would recommend to create an issue in the Angular CLI repository: https://github.com/angular/angular-cli/issues so the Angular CLI team can have a look at it and other Windows users can jump in. I am unable to reproduce the error on my system, but I’m using a Mac instead of Windows. Thanks Jithu!

          • Jithu Reddy

            Okay well thank you. I think i’m not clear with the question in earlier conversation. Let me repeat it once again I created MY-APP project based on your article but i’m missing Shared/index.ts in src/app/..

            Looking forward for your reply.

            thank you.

          • jvandemo

            @jithureddy:disqus – I’m afraid there is little I can do if you run the command and it does not generate the expected files on your system. I would check the version of Angular CLI you are running to see if it matches the version in this article, by running `ng version`. If it matches, and you still get inconsistent results, I would recommend to create an issue so the Angular CLI team can have a look at it. Does that make sense? Thanks!

          • Jithu Reddy

            did you understand my problem.

          • Jithu Reddy

            Hi@jvandemo

            When i create a new directory using ng new command shared file in App is missing in the created directory.

          • jvandemo

            The issue seems to be introduced with node v7: https://github.com/nodejs/node/issues/9542. From what I understand, it is not an issue with Angular CLI and downgrading to Node v6.9.1 would solve the problem.

  • Renato Perez

    Actually this is the ultimate guide to ng cli
    I’ve had used the cli before but today learned stuff
    I’m gonna use it as reference for future talks
    Appreciated Jurgen…

    • jvandemo

      Thank you @disqus_cCyS4fnkqd:disqus, really appreciate your kind words.

  • zpydee

    I have a core module in my project that contains services and models that will be applicable to both my web project as well as my ionic project and I’d like to pull this out into its own separate project so i can have a single code base that i can build and use in both. How do I go about this using angular-cli. My proposed project wouldn’t include anything like platformDynamic in the main.ts so I assume it would need other things. Any guidance would be appreciated. If you can direct me to a similar project setup, that’d be great.

    • jvandemo

      @zpydee:disqus – Angular CLI currently does not yet support the creation of shared libraries, but it is part of the roadmap so creating libraries will be possible at some point in the future. Meanwhile, the Angular 2 library generator may be of benefit to you: https://github.com/jvandemo/generator-angular2-library. This generator allows you to create a shared Angular 2 library. Hope that helps!

      • zpydee

        brillant, thanks – i’ll check that out.

        • jvandemo

          @zpydee:disqus – Good luck, feel free to let us know how it goes. Thanks!

  • Great Post on a great tool.
    Really like “What happens behind the scenes is”
    Angular CLI do stuff for us but’s it’s necessary to know what it does

    • jvandemo

      Thank you @chtisuisse:disqus, happy to hear that!

  • Martin_H_Andersen

    Thanks for taking the time to write the best documentation on the net for the angular-cli. Much better than the official documentation. It’s a keeper

    • jvandemo

      @Martin_H_Andersen:disqus Thank you for your kind feedback, Martin. Much appreciated!

  • VijayaKumar Raja

    Excellent article, explained clearly how to use angular-cli, Thank a ton :-)

    • jvandemo

      Thank you, really appreciate your kind words.

  • Weiqin Xie

    Why doesn’t my “ng g module” command generate components like examples?

    ng generate module admin
    installing module
    create src/app/admin/admin.module.ts

    nothing else below…

    • jvandemo

      The `ng generate module` command only generates the module boilerplate code.

      If you wish to add components to your new admin module, you can:

      $ ng generate module admin # create new module
      $ cd src/app/admin # navigate to new module directory
      $ ng generate component dashboard # create new component in admin module

      Hope that helps! Thanks!

  • Ranjit Mamidi

    Nice Article and this helps a new person to understand CLI very clearly.

    One problem I see with CLI ng build is it always includes the required scripts in index.html in absolute manner.
    When we move the final set of deployable files to any web server we will end up creating a new folder(application-name) and place all the generated files in this folder.
    Now index.html will not load properly as the it still expect the required scripts in home directory rather than the new application folder created.

    Example :
    Consider angular-test is my application name and
    angular-test/index.html looks like below



    Loading…

    but
    inline.bundle.js,vendor.bundle.js,main.bundle.js” were referred to be root folder instead of angular-test folder.

    My application worked when i updated my index.html like below



    Loading…

    I am not sure how to get the context or application name added to index.html while ng build when angular CLI is used.

    Any help or solution to my issue ….

    • jvandemo

      You can use the `apps.deployUrl` key in `angular-cli.json` to set the public path of your resources, for example:

      “outDir”: “dist”,
      “deployUrl”: “angular-test”,

      The `deployUrl` maps to the webpack output.publicPath setting that is described here: https://github.com/webpack/docs/wiki/configuration#outputpublicpath.

      Hope that helps! Thanks!

      • Ranjit Mamidi

        Thanks Let me try.

        • jvandemo

          Great, feel free to let us know how it goes. Good luck!

  • Eduardo Romeiro

    this should be the readme for the cli repo. alot of great stuff in here thanks Jurgen!

    • jvandemo

      Thank you for your kind words, much appreciated!

  • Richard Snazell

    Thanks @jvandemo, great article!

    • jvandemo

      Thank you, Richard, much appreciated!

  • Sébastien Côté

    I would be nice if you could maintain this documentation. Since your publication sereral things have changed like the github-pages command. This command doesn’t exist in the latest version of angular-cli.

  • Dirk Decher

    Great article, is there a way that I can include a preoprcessor like a template parser (ex. pug/jade) into the build process. Current I’m using the file watcher in my IDE but it would be nice if I just can avoid to produce the HTML files in the development folder self.
    Thanks a lot

    • jvandemo

      @dirkdecher:disqus – Thank you – there is a thread in the Angular CLI repository about a possible pug/jade integration: https://github.com/angular/angular-cli/pull/2205. It isn’t officially supported yet, but there seems to be (unofficial) interest to do make it happen. Thanks again!

  • Guest

    Great article, but please update to current @angular/cli setup.

    • jvandemo

      We will definitely do that. This article will be updated regularly to stay up to date with the latest developments. Thank you for your feedback.

  • Ivan Juarez

    This is great, why don’t you do another version of the same page but with new updates, regards.

    • jvandemo

      @disqus_5aSMhXj3gS:disqus – We will update this page with the latest updates as Angular CLI moves on so we have a central article that contains the latest information. Thank you for your feedback!

  • rajan

    very useful.. i learn a lot… thanks a lot…

    • jvandemo

      Thank you, we really appreciate your kind words.

  • raghavendra eluri

    Any thoughts on integrating JQuery based application as a stand alone component in angular 2 application.

    • jvandemo

      I think that is very dependent on the jQuery application and too specific to answer in a general comment. Thanks!

  • Łukasz Dramiński

    Thaks you for article, but i want ask when should I put libraries? In assets? How is a coret way.

    • jvandemo

      If you are referring to Angular libraries, you can `npm install` a library and then `import` it in your application and specify it in the `imports` array of the module you wish to load it in.

      If you are referring to a library that you would load via a element, then you can add it to the `scripts` property in angular-cli.json.

      Hope that helps? Thanks!

  • Jainam Jhaveri

    When do the scripts inside script tag actually get executed during AOT ?

    In one of my components, I have used minified amazon s3 sdk.
    In JIT, my app is working fine when I use

    declare let AWS: any;

    But in AOT it produces following error:
    Cannot read property ‘S3’ of undefined
    TypeError: Cannot read property ‘S3’ of undefined.

    Any idea why?

  • Sid By

    Great Article. I learned lot out of this article. Thanks

    • jvandemo

      Thank you, we really appreciate your kind feedback.

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.