34,79 €
Your quick, no-nonsense guide to building real-world apps with Angular 2
This book is targeted at web developers who want to build the next generation of state-of-the-art mobile and desktop web applications with Angular 2. This book does not require you to have prior exposure to either Angular 1.x or 2, although comprehensive knowledge of JavaScript is assumed. It's great for newcomers to Angular who learn best through clear explanations and definitions of concepts.
Angular 2 was conceived as a complete rewrite in order to fulfill the expectations of modern developers who demand blazing fast performance and responsiveness from their web applications.
This book will help you learn the basics of how to design and build Angular 2 components right from the beginning, providing full coverage of the TypeScript syntax required to follow the examples included. From that point on, we will build upon our first components, interconnect them, and give shape to larger web applications. We will then move to implementing routing in Angular 2, analyzing how to handle application states, and navigating from one component to another in depth. After this, the book features full coverage of web forms and user input validation, later leveraging all of this information to go through the basics of implementing user authentication in Angular 2 and providing a bird's eye view of the different strategies at hand to secure pages and areas of your website. Animating components and DOM elements with Angular 2 is also covered in this book. The final part of this book provides broad insights into how to unit test components and other modules such as services, directives, routes or pipes.
This book covers everything there is to know about getting well-acquainted with Angular without bogging you down. Everything is neatly laid out under clear headings for quick consultation, offering you the information required to understand a concept immediately, with short relevant examples of each feature.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 445
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2016
Production reference: 2260516
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-207-4
www.packtpub.com
Author
Pablo Deeleman
Reviewer
Johannes Weber
Commissioning Editor
Sarah Crofton
Acquisition Editor
Reshma Raman
Content Development Editor
Samantha Gonsalves
Technical Editor
Mohita Vyas
Copy Editors
Roshni Banerjee
Akshata Lobo
Project Coordinator
Sanchita Mandal
Proofreader
Safis Editing
Indexer
Priya Sane
Graphics
Kirk D'Penha
Production Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
Pablo Deeleman is a former UX designer and frontend engineer who discovered the Web back in the 90s, when a 14,400 bps modem was the key to an unparalleled world of marvels and a build-your-own-website was the name of the game.
After getting his BA (Hons) degree in marketing and moving through different roles in the advertising arena, he took his chance and evolved into a self-taught, passionate UX designer and frontend developer with a crunch for beautifully crafted CSS layouts and JavaScript thick clients, having produced countless interactive designs and web desktop and mobile applications ever since.
During these years, he has fulfilled his career as both an UX designer and frontend developer by successfully leading Internet projects for a wide range of clients and teams, encompassing European online travel operators, Silicon Valley-based start-ups, international heavy-traffic tube websites, global banking portals, or gambling and mobile gaming companies, just to name a few. At some point along this journey, the rise of Node.js and single-page-application frameworks became a turning point in his career, being currently focused on building JavaScript-driven web experiences.
After having lived and worked in several countries, Pablo Deeleman currently lives in Barcelona, Spain, where he leads the frontend endeavor in the Barcelona studio of Gameloft, the world leader in mobile gaming, and the home of internationally acclaimed games, such as Despicable Me: Minions Rush and Asphalt 8.
When not writing books or taking part in industry events and talks, he spends most of his time fulfilling his other passion: playing piano and guitar.
The book you hold in your hands right now is the result of a lot of time, effort, and sacrifice. Someone wisely said once that writing a book about a framework in the alpha stage is like aiming at a moving target, and indeed it is. During the writing, the author and the team involved in this project wound up losing track of how many times we had rewritten everything to conform to the latest incarnation of the framework. In the heat of the battle, it is quite easy to fall under the weight of frustration and seriously consider whether such a project is worth the effort or not. In that sense, this is why I only have words of appreciation for the team at Packt and most particularly for Samantha Gonsalves. Her kind words of support fueled the energy I needed to move this project ahead.
I would also like to specially thank my friend and tech author Jorge Ferrando for his guidance and hints during the production process for this book. His expertise in Angular 2 became priceless when assessing the different courses of action to deliver the best learning experience. A mention is required as well for our other fellow developers Javier Gómez, Alfonso Fernández, Fran Iruela, and Pedro Narciso.
I'd like to also thank the people who have mentored me and accompanied me along this professional journey over these years, with a special mention for the people at Casumo and Gameloft, and most specifically and in no particular order, for Razmus Svenningson, Kim Larsen, Josef Galea, Steve Attard, Iden Azzopardi, Renald Dalli, Matthew Borg, Mark Busuttil, Gerard Giné, Antonio González, Albert Puértolas, Rafael Marfil and the always inspiring Stuart Langridge.
Johannes Weber is a passionate developer and adviser in the field of web technologies spotlighted on enterprise JS apps. He works for Mayflower GmbH (Munich, Germany), where he focuses on the migration of SPA and MPA. In his free time, he (co)organizes the AngularJS Munich meetups, AngularCamp and JS-Kongress.de. Johannes cofounded ESnextNews.com, where you get five great ECMAScript.next links every week in your inbox.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
This book is dedicated to my parents Paul and Pepa, and in the loving memory of my brother José Raúl.
You will live forever in our hearts.
Over the past years, Angular 1.x has became one of the most ubiquitous JavaScript frameworks for building cutting edge web applications, either big or small. At some point, its shortcomings with regard to performance and scalability became too prominent as soon as applications grew in size and complexity. Angular 2 was then conceived as a full rewrite from scratch to fulfill the expectations of modern developers, who demand blazing fast performance and responsiveness in their web applications.
Angular 2 has been designed with modern web standards in mind and allows full flexibility when picking up your language of choice, providing full support for ES6 and TypeScript, but working equally well with today's ES5, Dart, or CoffeeScript. Its built-in dependency injection functionalities let the user build highly scalable and modular applications with an expressive and self-explanatory code, turning maintainability tasks into a breeze, while simplifying test-driven development to the max. However, where Angular 2 stands out is when it shows off its unparalleled level of speed and performance, thanks to its new change detection system that is up to five times faster than its previous incarnation. Cleaner views and an unsurpassed standards-compliant templating syntax compound an endless list of powerful features for building the next generation of web mobile and desktop apps.
Angular 2 is here to stay and will become a game changer in the way modern web applications are envisioned and developed in the years to come. However, and due to its disruptive design and architecture, learning Angular 2 might seem a daunting effort to newcomers.
This is where this book comes in—its goal is to avoid bloating the reader with API references and framework descriptions, but to embrace a hands-on approach, helping the reader learn how to leverage the framework to build stuff that matters right from day one. This is learning by doing right from the start.
This book aims to give developers a complete walkthrough of this new platform and its TypeScript-flavored syntax by building a web project from back to forth, starting from the basic concepts and sample components and iterating on them to build up more complex functionalities in every chapter until we launch a complete, tested, production-ready sample web application by the end of the book.
Chapter 1, Creating Our Very First Component in Angular 2, introduces the reader to web components, which are the building blocks of all Angular 2 applications.
Chapter 2, Introducing TypeScript, instructs the reader about the syntax and particularities of this typed superset of ECMAScript 6, being in fact the syntax of choice of the Angular team for building Angular 2.
Chapter 3, Implementing Properties and Events in Our Components, describes how our components behave like state machines that can change their state by receiving data through their input properties and emit data as events through their output properties.
Chapter 4, Enhancing our Components with Pipes and Directives, gives a complete walkthrough of the framework's built-in pipes used to digest data output in our templates, and also the built-in directives that provide advanced functionality to our component. The reader will also learn how to create custom pipes or directives
Chapter 5, Building an Application with Angular 2 Components, devotes an entire chapter to recap what we have learned so far and orchestrates everything to ensure our Angular 2 projects scale well regardless their size and conform to the community coding and naming conventions.
Chapter 6, Asynchronous Data Services with Angular 2, teaches the reader how to implement and deploy HTTP connections with other data services by means of the Http module, so we can create our own data service clients.
Chapter 7, Routing in Angular 2, introduces the reader to Angular 2's router and its built-in directives, providing a complete walkthrough the different strategies we have to load components from routes and handle the state through the History API.
Chapter 8, Forms and Authentication Handling in Angular 2, illustrates the different strategies we have at our disposal to build web forms with Angular 2, manage two-way data binding on input controls, and create complex forms and validations.
Chapter 9, Animating Components with Angular 2, covers the currently available tools and classes for implementing animations on our components, from pure CSS animations handled with Angular 2 directives to more complex transitions purely managed through JavaScript, thanks to Angular 2 animation builders.
Chapter 10, Unit Testing in Angular 2, will guide the reader through the steps required for implementing a sound testing foundation in our application, and the general patterns for deploying unit tests on components, directives, pipes, routes, and services.
In order to develop the examples contained in this book, you will primarily need a web browser updated to its latest version. We recommend Google Chrome or Mozilla Firefox, although Angular 2 is meant to be supported in all evergreen browsers.
You will also need terminal software installed on your OS, since many operations are handled through npm commands to the console. In this sense, having Node.js and npm installed on your system will be required to run most of the console commands mentioned in the book. The rest of modules required and their installation procedure will be described as we go.
Last, but not least, you will require a text editor to code your Angular 2 modules, although Chapter 1, Creating Our Very First Component in Angular 2 will provide a thorough walkthrough of all the best IDE alternatives in store nowadays for developing Angular 2 applications.
This book is targeted at web developers who want to build the next generation of state-of-the-art mobile and desktop web applications with Angular 2. This book does not require you to have prior exposure to either Angular 1.x or 2, although comprehensive knowledge of JavaScript is assumed. It's great for newcomers to Angular who learn best through clear explanations and definition of concepts.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "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."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The learn section gives us access to a quick tutorial to get up to speed with the language in no time."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from GitHub at https://github.com/deeleman/learning-angular2.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Unless you were lost in space for the past couple of years, chances are you are well aware of the momentum that modern JavaScript web frameworks and libraries have got in the frontend arena nowadays. We have even reached a stage where a new framework is born every day, forcing frontend developers to assess carefully whether this new cutting-edge code toolkit adds enough value to justify the time and effort required to face its learning curve and put it to good use in our next project.
Eventually, a handful of names ended up gaining more relevance than the rest. We are obviously referring to client-side frameworks that will probably sound pretty familiar to you already: Backbone, Ember, Knockout, Angular 1, and so on.
As the battle for supremacy in the JavaScript world carried on, new frameworks such as React or Aurelia entered the game, favoring web components and harnessing the power of Shadow DOM as the cornerstone of its architecture. Applications built this way proved to be more modular, scalable, and maintainable, let alone their unparalleled level of performance.
Angular 1 had come a long way already since its inception and its shortcomings had become too prominent to be overlooked any longer. It was time for something better and a simple revamp of codebase did not suffice. A more ambitious approach was required and Angular 2 was developed—a new framework engineered from scratch, which fully embraces the newest trends in the industry. It has web components at the heart of its design and it harnesses the power of Shadow DOM to maximize the responsiveness of our web entities against state changes. On top of that, Angular 2 offers a state-of-the-art change detection system baked in to each component, which is responsible for propagating bindings throughout the tree of components that comprise our applications.
The defining traits of Angular 2 go beyond the concept of just being a mere web components framework, since its features encompass pretty much everything you need in a modern web application: component interoperability, universal support for multiple platforms and devices, a top-notch dependency injection machinery, a flexible but advanced router mechanism with support for decoupling and componentization of route definitions, advanced HTTP messaging, and animation or internationalization, just to name a few.
In this chapter, we will:
As mentioned before, Angular 2 represents a full rewrite of the Angular 1.x framework, introducing a brand new application architecture completely built from scratch in TypeScript, a strict superset of JavaScript that adds optional static typing and support for interfaces and decorators.
In a nutshell, Angular 2 applications are based on an architecture design that comprises trees of web components interconnected between them by their own particular I/O interface. Each component takes advantage under the covers of a completely revamped dependency injection mechanism. To be fair, this is a simplistic description of what Angular 2 really is. However, the simplest project ever made in Angular is cut out by these definition traits. We will focus on learning how to build interoperable components and manage dependency injection in the next chapters, before moving on to routing, web forms, or HTTP communication. This also explains why we will not make explicit references to Angular 1.x throughout the book. Obviously, it makes no sense to waste time and pages referring to something that will not provide any useful insights on the topic, besides the fact we assume that you might not know about Angular 1.x, so such knowledge does not have any value here.
Web components is a concept that encompasses four technologies designed to be used together to build feature elements with a higher level of visual expressivity and reusability, thereby leading to a more modular, consistent, and maintainable web. These four technologies are as follows:
In theory, an Angular 2 component is indeed a custom element that contains a template to host the HTML structure of its layout, the latter being governed by a scoped CSS style sheet encapsulated within a Shadow DOM container. Let's try to rephrase this in plain English. Think of the range input control type in HTML5. It is a handy way to give our users a convenient input control for entering a value ranging between two predefined boundaries. If you have not used it before, insert the following piece of markup in a blank HTML template and load it in your browser:
You will see a nice input control featuring a horizontal slider in your browser. Inspecting such control with the browser developer tools will unveil a concealed set of HTML tags that were not present at the time you edited your HTML template. There you have an example of Shadow DOM in action, with an actual HTML template governed by its own encapsulated CSS with advanced dragging functionality. You will probably agree that it would be cool to do that yourself. Well, good news is that Angular 2 gives you the toolset required for delivering this very same functionality, so we can build our own custom elements (input controls, personalized tags, and self-contained widgets) featuring the inner HTML markup of our choice and a very own stylesheet that does not affect (nor is impacted) by the CSS of the page hosting our component.
Angular 2 applications can be coded in a wide variety of languages and syntaxes: ECMAScript 5, Dart, ECMAScript 6, TypeScript, or ECMAScript 7.
TypeScript is a typed superset of ECMAScript 6 (also known as ECMAScript 2015) that compiles to plain JavaScript and is widely supported by modern OSes. It features a sound object-oriented design and supports annotations, decorators, and type checking.
The reason why we picked (and obviously recommend) TypeScript as the syntax of choice for instructing how to develop Angular 2 applications in this book is based on the fact that Angular 2 itself is written in this language. Being proficient in TypeScript will give the developer an enormous advantage when it comes to understanding the guts of the framework.
On the other hand, it is worth remarking that TypeScript's support for annotations and type introspection turns out to be paramount when it comes to managing dependency injection and type binding between components with a minimum code footprint, as we will see further down the line in this book.
Ultimately, you can carry out your Angular 2 projects in plain ECMAScript 6 syntax if that is your preference. Even the examples provided in the book can be easily ported to ES6 by removing type annotations and interfaces, or replacing the way dependency injection is handled in TypeScript with the most verbose ES6 way.
For the sake of brevity, we will only cover examples written in TypeScript and actually recommend its use because of its higher expressivity thanks to type annotations, and its neat way of approaching dependency injection based on type introspection out of such type annotations.
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.
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.
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:
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:
These dependencies may evolve without prior notice so please refer to the GitHub repository for the most up-to-date list of requirements.
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:
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:
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:
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.
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.
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:
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:
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.
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:
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:
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.
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.
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:
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 thenew 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:
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:
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.
