Setting up our workspace

Before jumping into the implementation of our very first and shiny Angular 2 component, we need to bring in all the tools we will require to implement software based on TypeScript, let alone the Angular 2 framework modules themselves.

First and foremost, create a folder and double check that the NPM CLI is available in your system and is properly updated to the latest stable version. Otherwise, please go to https://nodejs.org and install the latest Node.js runtime.

Note

At the time of writing, the Angular 2 framework is in Release Candidate 1 version, so the requirements for building and deploying the examples contained in this book might have changed overnight. The author maintains a code repository at https://github.com/deeleman/learning-angular2, where you can check the most up-to-date version of each example contained in this book. The repository is divided into chapter folders and each folder contains the incremental version of the project as it is at the end of each chapter. Please refer to the code repository should any problem arise upon installing or deploying the examples in the book.

Installing dependencies

Our first requirement will obviously be to install Angular 2 onto our workspace, including its own peer dependencies. The Angular 2 team has made a great effort to ensure the installation is modular enough to allow us to bring only what we need, becoming our projects more or less lean depending on the requirements.

In this sense, Angular 2 does not come in the form of a single installable package, but many. This gives the smart developer the opportunity to pick only those modules that are required for its project, minifying the overall dependencies footprint. Some of these packages, such as common or core, are required regardless the type of project we want to ship. Some others, such as platform-browser-dynamic, are bound to the type of project and target platform addressed. A nonthorough list of the most common packages that you will require in your projects is given here:

  • @angular/core: This is the most relevant package, encompassing the backbone of Angular and its most common elements, such as directives and components. You will need to rely on this module on a common basis to import the basic elements of Angular 2 into your project.
  • @angular/common: You will seldom need to explicitly import tokens from this module, but it is worth remarking that this package contains the definitions of all the directives, services, and pipes contained by Angular 2, among other relevant classes.
  • @angular/compiler: Same as common, you will rarely import tokens explicitly from this module, although it is the one responsible for compiling the HTML templates and turning them into code that can render the application's UI output.
  • @angular/platform-browser: This module contains classes and functions required for composing and interacting with the DOM in a web browser context. Updating the page title or configuring the touch gestures setup are common actions made possible by this module. This package also contains the functions required to compile templates offline in production environments.
  • @angular/platform-browser-dynamic: We will rely thoroughly on this module during the course of the book, since it will provide us with the bootstrapping function we will require to initialize our applications on development.
  • @angular/http: It is the Angular 2 HTTP client, which we will cover in detail in Chapter 6, Asynchronous Data Services with Angular 2.
  • @angular/router: It is the Angular 2 built-in router still under Beta at the time of this writing.
  • @angular/router-deprecated: A snapshot of the previous incarnation of the Angular 2 built-in router, made available to ensure backward compatibility with existing applications. Chapter 7, Routing in Angular 2, will cover it in detail and explain some of its most remarkable differences with the new router still under development.

At the time of writing, these are all the different third-party libraries that are required as peer dependencies in an Angular 2 project, apart from the Angular 2 modules:

  • es6-shim: This introduces ECMAScript 6 compatibility polyfills for legacy JavaScript engines (mostly Microsoft Internet Explorer). This dependency is now required because many major browsers still do not provide wide support for ECMAScript 6 features, but hopefully, this will change soon. Some other implementations use the core-js standard library instead. Ultimately, pick the one you like the most as long as it properly polyfills the core ES2015 APIs required by Angular 2.
  • zone.js: This is a polyfill for the Zone specification that is used to handle change detection in Angular 2 applications.
  • reflect-metadata: This brings support for decorators in our Angular 2 classes and metadata reflection in our components. We will see decorators in action later on in this chapter and a broader overview of its different types and implementations in Chapter 2, Introducing TypeScript. Decorators are a core part of Angular 2.
  • rxjs: This library was developed by Microsoft Open Technologies, Inc. According to Microsoft, it is a set of libraries to compose asynchronous and event-based programs using observable collections and Array#extras style composition in JavaScript. In short, RxJS is a library for managing Observables, which allow us to make our applications fully reactive to asynchronous state changes. The Observables spec will be standardized by modern browsers in the future, so we will be able to rule out this dependency by then.

These dependencies may evolve without prior notice so please refer to the GitHub repository for the most up-to-date list of requirements.

Note

You will be probably surprised by the amount of libraries that Angular 2 does need and the fact that these dependencies are not part of the Angular bundle itself. This is because these requisites are not specific to Angular 2, but of a vast majority of modern JavaScript applications nowadays.

With all these dependencies and third-party libraries in mind, you can run the following set of bash commands in your terminal console, once you have created a folder for the project we will cover in this book:

$ mkdir learning-angular2
$ cd learning-angular2
$ npm init
$ npm install @angular/common @angular/core @angular/compiler --save
$ npm install @angular/platform-browser @angular/platform-browser-dynamic --save
$ npm install @angular/router @angular/router-deprecated --save
$ npm install @angular/http --save
$ npm install es6-shim reflect-metadata rxjs zone.js --save

Apart from the dependencies enlisted previously, we will also need to install the systemjs universal module loader package in order to support module loading between code units once transpiled into ES5. The systemjs package is not the only option available for managing module loading in Angular 2. In fact, we can swap it for other module loaders, such as WebPack (https://webpack.github.io/), although all the examples provided in this book make use of SystemJS for handling code injection. We will install SystemJS, flagging it as a development dependency by executing the following command:

$ npm install systemjs –save

Last, but not least, we will also install Bootstrap in our application so that we can easily craft a nice UI for the example application we will build incrementally in each chapter. This is not an Angular 2 requirement, but a particular dependency of the project we will carry out throughout this book:

$ npm install bootstrap –save

The installation can throw different alerts and warnings depending on the versions of each peer dependency required by Angular 2 at this moment in time, so in case of issues, I strongly recommend to fetch the latest version of the package.json file available in this book's code repository https://github.com/deeleman/learning-angular2/blob/master/chapter_01/package.json.

Download the file to your directory workspace and run the npm install command. NPM will find and install all the dependencies for you automatically.

Note

Mac OS users, who have not claimed ownership rights on the npm directory located at /usr/local/bin/npm (or /usr/local/npm for those users on OS versions prior to Mac OS El Capitan), might need to execute the npm install command with sudo privileges.

Installing TypeScript

We have now a complete set of Angular 2 sources and their dependencies, plus the Bootstrap module to beautify our project and SystemJS to handle module loading and bundle generation.

However, TypeScript is probably not available on your system yet. Let's install TypeScript and make it globally available on your environment so that we can leverage its convenient CLI to compile our files later on:

$ npm install -g typescript

Great! We're almost done. One last step entails informing TypeScript about how we want to use the compiler within our project. To do so, just execute the following one-time command:

$ tsc --init --experimentalDecorators --emitDecoratorMetadata --target ES5 --module system --moduleResolution node

Basically, we have just initialized a TypeScript project (which is our Angular 2 project itself) with support for experimental decorators (as we mentioned already, these are a new feature in ES7 and TypeScript that Angular 2 uses extensively) and set SystemJS as the default mechanism for importing modules and dependencies between files.

As a result of this action, we will find a new tsconfig.json file at the root of our project, including the settings required by the TypeScript compiler to transpile the component code into plain ECMAScript 5 JavaScript code readable by current browsers.

Note

Please remember that our browsers do not provide support for TypeScript or ECMAScript 6 out of the box, so we will transpile our code to some flavor of JavaScript that is widely supported by our target browsers.

A sneak peek on such file will yield the following:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "outDir": "built",
    "rootDir": ".",
    "sourceMap": false
  },
  "exclude": [
    "node_modules"
  ]
}

Simple, right? The set of properties included in our config manifest is self-descriptive enough, but we can highlight three interesting properties. They are as follows:

  • rootDir: This points to the folder the compiler will use to scan for TypeScript files to compile (currently the base folder in our example).
  • outDir: This defines where the compiled files will be moved unless we define our own output path by means of the --outDir parameter in the command line, the compiler will default to the built folder created at runtime in the same location where the tsconfig.json file lives.
  • sourceMap: This sets the source code mapping preferences to help debugging.

Toggle its value to true if you want source map files to be generated at runtime to back trace the code to its source through the browser's dev tools in case exceptions arise.

Besides these properties, we also can see that we have marked the node_modules folder as excluded, which means that the tsc command will skip that folder and all its contents when transpiling TypeScript files to ES5 throughout the application tree.

Tip

I would encourage you to refer to the TypeScript compiler wiki at https://github.com/Microsoft/TypeScript/wiki/Compiler-Options for a full rundown of options available in the compiler API.

Installing TypeScript typings

Besides the project dependencies, such as Bootstrap and Angular 2's own dependencies, TypeScript does require some additional libraries so we can get the best out of it. Specifically, ES6 extends the JavaScript environment with methods and APIs that need to be described to the TypeScript compiler. Otherwise, it will not recognize them as part of the syntax and will throw errors upon compiling. Whenever we need to instruct the TypeScript compiler about a JavaScript API, either a native one or any other API belonging to a third party library, we will want to use a TypeScript type definition file.

A TypeScript type definition file is basically a file with the d.ts file extension that contains TypeScript interfaces (more on this in Chapter 2, Introducing TypeScript) so we can better perform real-time type checking and prevent compiler errors. Installing type definition files in our projects is not a big deal and just requires having a typings tool installed in our environment. In fact, we need to install a type definition file to ensure that the TypeScript compiler is acquainted with the most up-to-date ES6 API. Good news is that we can install a TypeScript definitions manager tool right from the NPM registry, so we can automate the process of searching, installing and deploying type definition files. Therefore, return to the console and proceed with the following commands:

$ npm install -g typings
$ typings install es6-shim --ambient --save

First, we install the typings tool globally and then we leverage the typings CLI to install the es6-shim types definition file into our project, creating the typings.json file that will store the references to the source origin for all type definition files we will install now and later on. A new folder named typings is created and it contains the definition files we require. Without them, basic ES6 features like the new functional methods of the Array class would not be available.

Before moving forward, we need to tackle one more step regarding the TypeScript typings. When installing type definition files, two façade files are generated by the CLI: typings/main.d.ts and typings/browser.d.ts. However, only one should be exposed to the TypeScript compiler. Otherwise, it will raise an exception after finding duplicated type definitions. Since we are building frontend applications, we will stick to browser.d.ts and exclude main.d.ts and its linked definition files by marking it as excluded at tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "outDir": "built",
    "rootDir": ".",
    "sourceMap": false
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ]
}

On the other hand, it is actually recommended to exclude the typings folder from your project distribution by including it in your .gitignore file, same as we usually do with the node_modules folder. You only want to include the typings.json manifest when distributing your app and then have all the installation processes handled by npm, so it is very convenient to include the type definition files installation as an action handled by the postinstall script in the package.json file. This way, we can install the npm dependencies and the definition files in one shot. The code is as follows:

"scripts": { 
  "typings": "typings",
  "postinstall": "typings install"
},

When taking this approach, the typings package should be included in the package.json as part of the development dependencies. Thus, reinstall it with the --save-dev flag. Again, please refer to the book code repository at GitHub to fetch the latest version of the package.json file for this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.166.74