Use the Angular CLI For Faster Angular 2 Projects

Creating Angular 2 projects has never been faster than with the Angular CLI

Free Course

Getting Started with Angular 2

Angular 2 is the shiny new framework that comes with a lot of new concepts. Learn all the great new features.

If you've ever gone through the Angular 2 Quickstart over the past year, you'll know that a big part of getting started with Angular 2 is the setup.

It included things like:

  • Creating our app files
  • Configuring TypeScript and Typings
  • Adding script tags for
    • Angular 2
    • Rx.js
    • System.js
  • Configuring System.js
  • Creating our Angular 2 component
  • Bootstrapping our Angular 2 application

Talk about a lot! Thankfully, at ng-conf 2016, the Angular team announced a tool that will make creating and scaffolding Angular 2 applications incredibly easy.

The Angular CLI cli.angular.io

Angular CLI Homepage

The Angular CLI effectively takes all those configuration and setup steps shown above and condenses it down into one quick line:

ng new scotchy-scotch

There are many things that the CLI can do so let's get it installed and walk through some features.

Installing the Angular CLI

To install the CLI, we'll use Node and npm.

npm install -g angular-cli

That's it! Now we can start using the CLI to build out our applications.

Starting a New Application

To start a new application, just run the command we saw earlier:

ng new scotchy-scotch

Angular CLI ng new

So what exactly does this do for us? Let's take a look at the newly generated folders and files:

// configuration files
|- config/
|----- environment.dev.ts
|----- environment.js
|----- environment.prod.ts
|----- karma-test-shim.js
|----- karma.conf.js
|----- protractor.conf.js

// end-to-end-tests
|- e2e/
|----- app.e2e.ts
|----- app.po.ts
|----- tsconfig.json
|----- typings.d.ts

// npm dependencies
|- node_modules/

// public facing app. built things go here
|- public/

// where most of the work will be done
|- src/
|----- app/
            |----- shared/
                        |----- index.ts
            |----- environment.ts
            |----- index.ts

            // our first generated component
            |----- scotchy-scotch.component.css|html|spec.ts|ts
|----- favicon.ico
|----- icon.png
|----- index.html
|----- main.ts
|----- manifest.webapp
|----- system-config.ts
|----- tsconfig.json
|----- typings.d.ts

// overall configuration
|- typings/
|- .clang-format
|- .editorconfig
|- .gitignore
|- angular-cli-build.js
|- angular-cli.json
|- package.json
|- tslint.json
|- typings.json

It's important to take note of this directory structure and where the files are located because the application that the Angular CLI generates follows the recommended app structure and style guide.

The majority of our application is under src/app. This is where we will be working and everything that gets compiled and is available to our final application will be built to the public folder.

Learn from this and incorporate these things into your own development. The Angular CLI will not only create the files and folders, it will also install any npm dependencies required.

Here is the default package.json that gets created:

{
  "name": "scotchy-scotch",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng server",
    "postinstall": "typings install",
    "lint": "tslint \"src/**/*.ts\"",
    "format": "clang-format -i -style=file --glob=src/**/*.ts",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.0.0-rc.1",
    "@angular/compiler": "2.0.0-rc.1",
    "@angular/core": "2.0.0-rc.1",
    "@angular/platform-browser": "2.0.0-rc.1",
    "@angular/platform-browser-dynamic": "2.0.0-rc.1",
    "@angular/router": "2.0.0-rc.1",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "0.19.26",
    "zone.js": "^0.6.12"
  },
  "devDependencies": {
    "angular-cli": "^1.0.0-beta.0",
    "clang-format": "^1.0.35",
    "codelyzer": "0.0.14",
    "ember-cli-inject-live-reload": "^1.4.0",
    "jasmine-core": "^2.4.1",
    "jasmine-spec-reporter": "^2.4.0",
    "karma": "^0.13.15",
    "karma-chrome-launcher": "^0.2.3",
    "karma-jasmine": "^0.3.8",
    "protractor": "^3.3.0",
    "ts-node": "^0.5.5",
    "tslint": "^3.6.0",
    "typescript": "^1.8.10",
    "typings": "^0.8.1"
  }
}

All those dependencies are added and included in our src/index.html file. All of the setup that was in the Angular quickstart are now taken care of for us.

Check out the index.html file and you'll see the scripts loaded and System.js started:

<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>

<script>
  System.import('system-config.js').then(function () {
    System.import('main');
  }).catch(console.error.bind(console));
</script>

ng new options

  • --dry-run (alias d): Only output the files created and operations performed. It doesn't actually create the project.
  • --verbose (alias v): Show more information
  • --skip-npm: Don't run any npm commands like installing dependencies
  • --skip-git: Don't create a new git repo for this project
  • --directory: Specify the directory you want to create this project in

Initialize a New Application

Let's say you already have a folder that you've started working in. The ng init command is here so that you can use the current folder you're already working in.

In the folder you are working in, run:

ng init scotchy-scotch

Let's talk about the options that we can use with ng init.

ng init options

  • --dry-run (alias d): Only output the files created and operations performed. It doesn't actually create the project.
  • --verbose (alias v): Show more information
  • --skip-npm: Don't run any npm commands like installing dependencies
  • --name: Name the new project you are creating

Serve Our Application

Another really cool thing that our CLI allows us to do is to serve our application in the browser. Previously, we would have to create a server using lite-server or create our own Node (or other) server.

The Angular CLI let's us do this with one simple command:

ng serve

Just like that, the Angular CLI will build a server for us with Node and open up our browser.

Angular CLI Serve Features

What features are given to us with our new server?

  • Built with BrowserSync: Reload on saves
  • Automatically routed for us
  • Found in the browser at http://localhost:4200
  • Simplicity and ease-of-mind

Generate Parts of Your Application

This is where things get interesting. So far we've just created and instantiated a new project. The ng generate command can do so much for us:

  • Create a new component
  • Create a new directive
  • Create a new route
  • Create a new pipe
  • Create a new service

That's a ton of functionality and helps speed up development. First let's talk about the options that we can use for all of the above.

ng generate options

  • --flat: Don't create the code in it's own directory. Just add all files to the current directory.
  • --route=<route>: Specify the parent route. Only used for generating components and routes.
  • --skip-router-generation: Don't create the route config. Only used for generating routes.
  • --default: The generated route should be a default route.
  • --lazy: Specify if route is lazy. default true

Now we can run through each and see exactly what gets created and how the Angular CLI makes life easier.

Generating a New Component

Components are the foundation of Angular development. Let's generate a new component:

ng generate component hello

Angular CLI ng generate component


Note: It's important to name your component simply. If a component is created with the name hello, these are the corresponding naming schemes:

  • Folder: hello
  • Files: `hello.component.[css,html,spec.ts,ts]
  • Class: HelloComponent

If you use ng generate component HelloComponent, then your component class will be an undesirable HelloComponentComponent.


Here are the files that get created:

|- src/
        |----- app/
                    |----- hello/
                                |----- shared/
                                            |----- index.ts
                                |----- hello.component.css|html|spec.ts|ts
                                |----- index.ts

Our new component is relegated to its own folder within the src/app folder.

Generating a New Route

Routes give us a top level view of our application. We can generate them with:

ng generate route about

Angular CLI ng generate route

Now we have our new files in a weird new folder under src/app. Our new folder is +about. What's up with that?

The + dictates that a folder will be lazy loaded (read more in the style guide. A typical lazy loaded folder contains a routing component, its child components, and their related assets and modules.

Routing is where the lazy loading takes place, and the route is generated for us via the CLI. Generating a route with the CLI generates a new component and its routing. Let's take a look at the src/app/+about folder:

|----- +about/
            |----- shared/
                        |----- index.ts
            |----- about.component.css|html|spec.ts|ts

That looks awfully similar to when we ran ng generate component hello. That's because it's a component, just like our HelloComponent.

Where does the routing come into play? We have to go to our top level component (the ScotchyScotchComponent in src/app/scotchy-scotch.component.ts).

You can see that the ROUTER_DIRECTIVES AND THE ROUTER_PROVIDERS were imported into our application, injected into our top-level component, and routed using the @Routes() decorator.

import { Component } from '@angular/core';
import { AboutComponent } from './+about';
import { Routes , ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'scotchy-scotch-app',
  templateUrl: 'scotchy-scotch.component.html',
  styleUrls: ['scotchy-scotch.component.css'],
  directives: [ROUTER_DIRECTIVES],
  providers: [ROUTER_PROVIDERS]
})
@Routes([
  {path: '/about', component: AboutComponent}
])
export class ScotchyScotchAppComponent {
  title = 'scotchy-scotch works!';
}

We don't have to worry about routing anything, or loading component files when a user visits that route. It's all loaded for us!

More Commands

As the CLI get's more hashed out and more information, we'll be filling out this section with more commands and what they do. Some of these commands were a little buggy when we first tested out the CLI since it's in v1.0.0-beta.1 at the time of this writing.

Here's the list of commands that we can also run:

  • ng build
  • ng test: Run unit tests with karma
  • ng e2e: Run end-to-end tests with protractor
  • ng get: Gets values for project
  • ng set: Sets values for project
  • ng github-pages:deploy: Build the app for production, setup GitHub repo, and publish
  • ng lint: Run codelyzer to analyze code
  • ng format
  • ng doc
  • ng version: Get the version of the CLI

Conclusion

The Angular CLI is an amazing tool and one that comes at a time when more and more people are getting into Angular 2 development. After all the announcments at ng-conf 2016, now is the time to dive in.

The CLI makes diving in that much more accessible since setup, which took up the majority of the time for first-time developers is now handled for us.

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.