Angular, TypeScript, SystemJS, and Browser Cache

I was writing a small app in Angular 2 in TypeScript with the on-the-fly transpiling by SystemJS. I needed to implement a router that would switch between the Home and ProductDetail views in a single page app.  The root component had two links and was supposed to render either Home or ProductDetail components depending on which link the user clicks. Angular 2 offers a pretty elegant syntax for this:


@Component({
    selector: 'basic-routing',
    directives: [ ROUTER_DIRECTIVES], 
    template: `<a [router-link]="['/Home']">Home</a>
              <a [router-link]="['/ProductDetail']">Product Details</a>
              <router-outlet></router-outlet>` 
})
@RouteConfig([
    {path: '/',        component: HomeComponent, as: 'Home'}, 
    {path: '/product/', component: ProductDetailComponent, as: 'ProductDetail'  } 
])
class RootComponent{}

Configure the router to map the component to a URL, use property binding in the form of [router-link], and specify the router outlet, where the content of one or the other component should be rendered. Nice and easy, isn’t it? Then I created a HomeComponent to render the text ‘Home Component’ , copy-pasted the code into ProductDetailComponent and started the app in the browser.

Running the app properly rendered the text Home Component, but when I clicked on the second link, nothing happened – the text Home Component remained in the browser window. Opened the code of the ProductDetailComponent. Oops… Forgot to change the text for rendering while copy-pasting – it still had ‘Home Component’. No biggies. Replaced it with ‘Product Detail Component’ and re-ran the app. Nothing changed. I still see Home Component no matter what link I click.

So what do we do with this nice syntax with Angular binding and TypeScript annotations? There is nothing to debug there. We need to debug the actual ES5 code that runs in the browser. Here’s the snapshot of my application window (on the left) after I clicked on the Product Detail link (Chrome Dev Tools panel is on the right):

ts1

Note that Angular router properly formed the URL for the product view. The template property in the file product.ts has the right content: ‘Product Detail Component’. Now let’s take a look at the content of the file product.ts!transpiiled, which was auto-generated by SystemJS:

ts2

This file was not regenerated and still has the ‘Home Component’ in the template property! Apparently, changing the string content is not a good enough reason for SystemJS to re-run the TypeScript transpiler and the browser used its cached version. Running the same example in FireFox worked as expected – its cache was clean so fresh ES5 files were generated by SystemJS.

Chrome Dev Tools has an option Disable Cache while Dev Tools open, and this would clear the cache on the page refresh. But if you want the browser cache to be refreshed even if the Dev Tools are not open, add the following lines between the head tags in your HTML file:

  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="Expires" content="0">

Manning opened the MEAP program for our upcoming book “Angular 2 Development with TypeScript”, where JSPM, SystemJS and TypeScript development is covered in greater details.

Starting an Angular 2 project with TypeScript and JSPM

New York City residents often say “It’s going to be a nice city when all the constructions will be finished”. The same applies to Angular 2 framework, which remains in Alpha (the latest build is 42 at the time of this writing). It has a potential to become a great framework in 2016, when the API will be stabilized and documented.

Writing code in Angular 2 is a lot simpler than in AngularJS, especially if you use TypeScript (see my blog on why writing in TypeScript here). But getting started with a new project is more complicated and requires a careful selection of tooling. in addition to a typical JavaScript project you need to take care of transpiling TypeScript and loading modules – neither of these steps can be done natively by the browsers. Hence you need introduce tooling into your develop-deploy process. For reasoning of using TypeScript read this blog.

Earlier this year I wrote a blog that included a scary list of tools that today’s JavaScript developers may use. In an effort of minimizing the number of required tool we settled on npm (for both installing packages and build scripts) and JSPM (a package manager that comes with the module loader SystemJS that comes with TypeScript transpiler). These are the steps that should be done before you start writing your Angular 2 app in TypeScript:

In the command window run the following npm command (install Node.js runtime if you don’t have npm):

1. Install JSPM globally on your computer (-g means global). It comes with SystemJS:

npm install jspm -g

2. Create a folder for your project, go there and ask jspm to generate all required configuration files:

jspm init

This command will ask you 8 question regarding the required configuration. Accept the defaults for the first 7 questions, but for the question about transpiler, enter typescript. After running this command in your folder you’ll find the new files config.js and package.json as well as the subfolder jspm_packages.

3. Install Angular 2 in your project folder and all required dependencies:

jspm install angular2 core-js css reflect-metadata

This command will download all of the above libraries inside the folder jspm_packages and will modify the content of the file config.js

4. Install an http server that will be serving your app to the browser:

npm install http-server -g

5. Create the file index.html with the following content:

<!DOCTYPE html>
<html>
 <head>
  <script src="//cdn.rawgit.com/systemjs/systemjs/0.19.4/dist/system.js"></script>
  <script src="//code.angularjs.org/2.0.0-alpha.40/angular2.js"></script>
  <script>
   System.config({
    transpiler: 'typescript',
    map: {typescript: '//cdn.rawgit.com/Microsoft/TypeScript/v1.6.2/lib/typescript.js'}
});

   System.import('main.ts');
  </script>
 </head>
 
 <body>
   <hello-world></hello-world>
 </body>
</html>

This code loads SystemJS and Angular (I used the build Alpha 40) and tells SystemJS to load the TypeScript 1.6.2 compiler from CDN, and load the file main.ts , which is shown next.

6. The Typescript file main.ts is your entry point to the application. It can import other files, but this would be a subject for a separate blog post. This is what you should enter in main.ts:

import {Component, bootstrap} from 'angular2/angular2';

@Component({
  selector: 'hello-world',
  template: `<h1>Hello {{ name }}!</h1>`
})
class HelloWorldComponent {
  name: string;

  constructor() {
   this.name = 'Angular 2';
  }
}

bootstrap(HelloWorldComponent);

The @Component annotation is all you need to to turn a class into a component. The selector property defines a name of the tag that represents this component in the HTML file. The template property defines the HTML to render. In this example the value of the variable name will be evaluated and inserted in the greeting using Angular binding.

7. Start your http server by entering http-server in the command line from your project directory and enter http://localhost:8080 in your Web browser you should see a Web page that reads Hello Angular 2! Here’s how it’s rendered in my Chrome browser with Developer Tools panel open:

HelloAngular2
As you see the TypeScript compiler was downloaded as a part of your application and the transpiling of the code was done on the fly.

In this simple example I didn’t install any TypeScript related tool to keep this example IDE-agnostic. But we do use IDEs and additional install of the tsd (type definition manager) and DefinitelyTyped library would be required as well so the context-sensitive help for your code and all third-party JavaScript libraries would be available.

I like the fact that JSPM and SystemJS are written by the same developer (Guy Bedford). With these tools the configuration process is automated, modules of different formats are seemlesly loaded, TypeScript is automatically transpiled, duplicate dependencies are not being loaded, and we can can get dependencies from multiple repositories. All this comes at a price of a couple of seconds delay before you see your page loaded in a browser.

JavaScript developers are spoiled by seeing their latest code changes deployed and rendered instantaneously. Coming out of a Java project that required minutes to see my code changes in action, I can live with these extra couple seconds. But opening the configuration files auto-generated by JSPM still gives me light goose bumps. There is too much stuff in there. Again, that Java project had Maven build scripts with thousands lines of code, so I can live (for now) with 300 lines in config.js in a Hello World project, but the search of the configuration holly grail continues…

Manning opened the MEAP program for our upcoming book “Angular 2 Development with TypeScript”, where JSPM, SystemJS and TypeScript are covered in greater details.

Why writing JavaScript applications in TypeScript

JavaScript is the language of the Web. There is no other language that can run literally on any old or new device connected to the Internet. On the other hand, there are dozens of languages that compile (a.k.a. transpile) to JavaScript. Why not just writing JavaScript applications in JavaScript? Let me start with analogy with Assembly.

Programs written in a particular flavor of Assembly language run on any device that have a CPU that understand it. See the shortcoming comparing to JavaScript? An Assembly program can’t run on any device, but on any device with a specific CPU architecture. Still, why not writing all the code for a specific platform in Assembly? Why use Java, C#, Python or C++?

We want to be productive. Vast majority of the programmers want to be as far as possible from the bare bone metal. Let compilers and virtual machines convert our programs to the machine code.

We want to be productive in writing JavaScript as well.

Compilers convert the source code into a byte code or a machine code. Transpilers convert a source code of a program in one language into a source code in another one.

You can think of any programming language (other than a machine code) as a syntactic sugar added on top of a another language. While compilers just dissolve all this sugar, transpilers dissolve only a part of it.

Last year I was experimenting with the Dart language. It has a nice syntax (easy for Java and C# developers), which transpiles to to JavaScript. I like Dart, but it requires a special browser with a VM during development. The other negatives are that Dart code transpiles into a difficult to read JavaScript and doesn’t offer easy interoperability with JavaScript frameworks that coexist with the Dart code in most of the applications.

TypeScript was designed by Anders Hejlsberg who also created C#, Delphi, and Turbo C++. TypeScript is a superset of JavaScript, which means that simply renaming existing .js into a .ts file will make it a valid JavaScript code. This is almost always the case except the cases described in this blog.

The TypeScript compiler tsc is actually a transpiler that generates easy to read JavaScript. TypeScript can be compiled into the ES#, ES5, or ES6 flavor of JavaScript, which is a simple option on the command line. You can run tsc in a so called watch mode, so it watches your files for changes and automatically compiles them as soon as you save the file.

Currently I use TypeScript for writing code that uses two frameworks by Google: Angular 2 (it’s written in TypeScript as well) and Polymer.

These are some reasons for writing JavaScript code in TypeScript:

* TypeScript supports types. This allows the TypeScript compiler help developers in finding and fixing lots of errors during development before even running the app.

* Creators of TypeScript follow the ECMAScript 6 standard,and TypeScript 1.6 already supports more than a half of the ES6 syntax. Also TypeScript enriches ES6 by adding types, interfaces, decorators, class member variables (fields), generics, and the keywords, public and private (well, private is not what some might think). See the roadmap of TypeScript.

* TypeScript interfaces allow to declare custom types that will be used in your application. Interfaces help in preventing errors caused by using the objects of wrong types in your application. This feature will be dear to the hearts of Java and C# developers although TypeScript interfaces can be use not only with the implements keyword, but used for presenting object types in a special way.

* The ability to have great IDE support is one of the main advantages that TypeScript has to offer. IDEs as well as some text editors offer great context-sensitive help. The code refactoring of TypeScript is done by IDEs whereas with JavaScript it has to be done manually.

* There is a library DefinitelyTyped that includes hundreds of type definitions files for TypeScript and allows IDEs to perform type checking and offer context-sensitive help while using APIs of literally all JavaScript frameworks.

* The generated JavaScript code is easy to read and looks as a hand-written code. Even though you can generate so called source maps that allow you to debug the TypeScript code inside the browser, you can easily read generated JavaScript and find the corresponding lines in your TypeScript program.

* TypeScript comes with a separate static code analyzer, and several IDEs or text editors already use it (e.g. WebStorm, Atom, Sublime Text, Visual Studio Code, Visual Studio 2015 et al.)

Anyway, today TypeScript is my language of choice for writing the source code for Web browsers. I’m planning to write a couple of more blogs introducing TypeScript syntax. If you want to play with TypeScript, visit http://www.typescriptlang.org.

If you’re a Java developer who kept postponing learning JavaScript till better times, the time is now. You can ease into the JavaScript world via the door marked “TypeScript”.

If you’re planning to work with Angular 2 and want to see how to use TypeScript with this framework, our upcoming “Angular 2 Development with TypeScript” book may come handy.

 

From Flex to Angular and Polymer

I’ve received an email from an enterprise Flex developer who’s looking to converting a number of applications to JavaScript. He asked a number of questions, and I decided to write a brief blog with the answers. His email started like this:

“We have a bunch of existing enterprise Flex web apps.
Since some of Flex libraries are not updated and no longer supported, first we try to find similar libraries in JavaScript and call them via iFrame.”

Below are his questions and my answers.

1) Do you see Flex -> Angular 1 transition as smart pragmatic move, or would recommend to wait till Angular 2 comes out?

Comparing Flex and Angular is not apples to apples. Besides being an architectural framework it included a number of rich and extendable UI components, which Angular doesn’t have. Angular will definitely help you in creating a Web application taking care of the navigation between the views, binding the data to the UI, and injecting services into your components. But this is pretty much it. It doesn’t have its own component that is often needed by the enterprise developers. This is one of the reasons why we started using Google’s Polymer for GUI components.

2) Does A2 has definite advantages over A1? Is it easier and has better tooling?

Yes, it’s easier to learn as Angular architecture is simplified greatly. A2 is component based. No need to worry about different scopes. Any service is a class. No need to create controllers in a special way: a class is a controller. Dependency Injection is easier to use – only constructor injection is allowed. The GUI for the component is specified in a class annotation and can be stored in a separate file. A2 rendering is separated from the rest of the framework code, so it’ll be possible to render not only HTML but the native UI as well (this feature is experimental for now).

3) When will A2 be released? Is it worth waiting for?

Currently, A2 is in its 35th build of Alpha. There are no official release dates, but I believe that A2 will go in Beta in October-November of this year. You can (and should) start developing in A2 today as long as the app doesn’t have to go into production this year. The API of this framework is still being changed so you may run into bugs here and there. But I’d recommend starting new projects in Angular 2.

4) Do you expect to have an easy upgrade from A1 to A2?

It may not be easy, but shouldn’t be overly complicated either. If you have resources you can upgrade existing apps to A2, but it’s not a must. You may live with two version of the app for some time.

5) When will you give an A2 class? When will your A2 book come out?

We were planning to run the A2 class online starting from the end of September, but since both my colleague/instructor/co-author and I have a day job plus a book project in the evenings, we decided to postpone the training until January.

Our book “Angular 2 Development with TypeScript” will be available as a part of Manning MEAP program in September. You’ll be able to buy it and get access to the drafts as we write them. So far we’ve written about 130 pages.

Now I’d like to add a brief comment about Polymer library from Google. Our company, Farata Systems, spent 9 years developing applications in Adobe Flex for different clients. Over these years we’ve created a library of smart GUI components that were not easily replaceable in JavaScript. During the last two years, we were evaluating different JavaScript alternatives but couldn’t find any that would allow us to leverage or experience and migrate our Flex components to JavaScript.

Being very pragmatic and careful, we’ve decided to see how difficult would be to re-create a Flex component in Polymer. Eight years ago we’ve created a combobox in Flex that could take an external data collection as a model and render its data as a grid when the user clicks on it. We gave this combobox to one of our developers, and he re-created it in Polymer relatively easily. Another developer started to work on a pilot project with Polymer and we also see good results.  What we don’t like in Polymer is the fact that it doesn’t support module loading. You have to use HTML imports. At the time of this writing,  our recommended set of languages/frameworks is TypeScript, Polymer, and Angular 2.

In September we’re planning to publish two technical articles describing our experience with Polymer. Farata Systems is a well-known name in the Flex community, and we’re going to build a good reputation in the JavaScript world as well.

A Toolbox of the Angular 2 Developer

Say you need to hire a Web developer experienced with Angular. What would you expect the developer to know? Well, he or she needs to know how to create Angular components, what’s data binding, dependency injection, routing et al. But this is just the tip of the iceberg. Below is a list of languages and tools that professional Angular developers use.

* JavaScript is a de-facto standard programming language for the front-end of Web applications. ECMAScript 6 (ES6) is the latest standardized specification for scripting languages and JavaScript is the most popular implementation of this spec.

* TypesScript is a superset of JavaScript that makes developers more productive. TypeScript 1.5 (currently in Beta) supports most of the features of ES6 and adds optional types, interfaces, meta-data annotations and more. The Angular 2 framework itself is written in TypeScript.

* DefinitelyTyped is a vast collections of files describing the API of 500+ libraries and frameworks. Using DefinitelyTyped allows the TypeScript compiler and IDEs know the types expected by the APIs of these libraries.

* Angular 2. It’s a complete re-write of a popular Angular 1.x. It’s currently in Alpha.

* Transpilers. Since most of the Web browsers support only the ECMAScript 5 syntax, you need to transpile (convert, compile one source code to another) the code written in TypeScript or ES6 to its ES5 version for deployment. Angular developers use Babel, Traceur, and the TypeScript compiler.

* SystemJS is a universal module loader, which load modules created in ES6, AMD or CommonJS standards.

* Node.js is a platform built on Chrome’s JavaScript engine. Node includes both a framework and a runtime environment to run JavaScript code outside of the browser. We don’t use the framework, but you can’t avoid using the Node runtime to install required tools for developing Angular applications.

* npm is a package manager that allows to download tools and reusable JavaScript modules. Npm has a repository of thousands modules, but we’ll mostly use it for installing developer’s tools, e.g. the TypeScript compiler, the task runner Gulp and more.

* Bower used to be a popular package manager for resolving application dependencies (e.g Angular 2, jQuery at al.). We don’t use Bower any longer as everything we need can be downloaded using npm.

* jspm is yet another package manager. Why do we need another package manager if npm and bower can take care of all dependencies? Modern Web applications consist of loadable modules and jspm integrates SystemJS, which makes loading modules a breeze.

* Grunt is a task runner. Lots of steps need to be performed between developing and deploying the code. All these steps must be automated. You may need to transpile the code written in TypeScript or ES6 into widely supported ES5 syntax. The code, images, and CSS files need to be minimized. You may want to include the tasks that will check the code quality and unit-test your application. With Grunt you configure all the tasks and their dependencies in a JSON file so the process is 100% automated.

* Gulp is a newer than Grunt task runner. It can automate all the tasks just as Grunt does, but instead of configuring the process in JSON you simply program it in JavaScript. This allows you to debug it if need be.

* jslint and eslint are code analyzers that looks for problematic patterns in a JavaScript program or JSON-formatted documents. These are code quality tools. Running a JavaScript program trough jslint or eslint results in a number of warning messages suggesting how to improve the code quality of this program.

* tslint is is a code quality tool for TypeScript. It has an collection of rules (can be extended) to enforce the recommended coding style and patterns.

* Minifiers make files smaller. For example, in JavaScript they remove comments, line breaks, and make variable names shorter. Minification can also be applied to HTML, CSS, and image files.

* Bundlers combine multiple files and their dependencies in a single file.

* Testing frameworks. Since JavaScript syntax is very forgiving, the application code requires testing. We use the Jasmine framework and the test runner called Karma.

* IDE. Both JavaScript and TypeScript are well supported by modern IDEs and text editors such as WebStorm, Visual Studio, Visual Studio Code, Sublime Text, Atom et al.

* Browser as a development environment. All major Web browser comes with developer tools that allow to debug your programs right inside the browser. We use Chrome Developer Tools.

* Web Components. This is the future of Web development. The goal is to develop reusable widgets for the Web application. We already started using the Polymer library of Web components in a pilot project and like it a lot.

This list may look intimidating, but it can be mastered one step at a time. Programming in Angular 2 is easier than in Angular 1.x, but the initial environment setup should be done right so you can really enjoy the development process.

Started working on the Angular 2 book

Over the past three years my colleagues and I prepared and delivered multiple trainings “Modern Web Development with AngularJS and Java“.  We felt pretty comfortable with the framework, and the training  was structured around building a sample Online Auction app with AngularJS on the front and Java EE on the back. During the last year we’ve developed and deployed in prod the Easy.Insure app using Google Dart and AngularDart.  So AngularJS became our framework of choice. When Google announced a complete re-write of the AngularJS, we were not disappointed. Angular 2 will make this framework  better.
Angular_cover

I’ll be writing this book with my colleague (and co-instructor) Anton Moiseev. This is going to be a tough project because Angular 2 is in Alpha now, and the API changes weekly, literally! I had this experience in 2006 while writing with my colleagues on a book on Adobe Flex 2, which went through one Alfa and three Beta versions while we were working on the book. We had to re-write code samples multiple times. It was a challenging but interesting project. Now we should do it again. It goes without saying that this book we’ll also write in a plain text editor using the Asciidoc markup and Asciidoctor for generating the HTML and PDF versions.

We want to thank Manning Publications for accepting our book proposal. Below is a short version of Table of Contents. So far only the Appendix on EcmaScript 6 is written, but by the end of July we should have the first three chapters ready as well.

1. Introducing Angular 2
  The landscape of client-side development
The history of Angular
Why choosing Angular 2
Architecture of Angular 2 applications
Introducing a sample Online Auction

2. TypeScript as a language for Angular applications
TypeScript as a superset of ECMAScript 6
Tooling

3. Getting started with Angular
Creating your first single-page application
Model-View-Component
Templates
Data binding
Setting up the development environment for Angular 2 applications
Hands-on: Getting started with Online Auction

4. Registering and creating objects
The Dependency Injection pattern
Angular Modules
Hands-on: Modularizing Online Auction

5. Navigation with Component Router
Changing views
Hash-based navigation
Deep-linking with HTML5 History API
Passing Parameters to Components
Authentication and the role-based navigation
Lazy-Loading Modules
Hands-on: Adding navigation to Online Auction

6. Bringing Together Data and Views with Data Binding
Connecting UI to the data
Benefits of data binding
Unidirectional vs. two-way data binding
Change detection
Data Binding in Templates
Hands-on: Binding data to views in Online Auction

7. User Interaction via Forms
Data entry
Form controls
Data-Driven Forms
From UI-driven to data-driven forms
Form validation
Hands-on: Offering products for sale

8. Communicating with Servers
Asynchronous HTTP requests
Working with RESTful services
Using WebSockets
Hands-on: Pushing bid notifications to the clients

9. Testing Angular applications
Developing without a compiler
Test runners
Testing frameworks
Working with mock objects
Troubleshooting Angular applications
In-browser debugging
Hands-on: Testing Online Auction

10. Deploying Angular Applications
Configuring Web servers for single page applications
Supporting HTML5 History API
Proxying HTTP requests
Cross-origin resource sharing
Hands-on: Deploying Online Auction

Appendix A. JavaScript Implementation of ECMAScript 6
The Scope of a Variable
Arrow functions
Rest parameters
Classes
Collections
Modules
Destructuring
Promises
Generators
Code conversion from ES6 to ES5 with Babel

Appendix B. Web Components
Shadow DOM
Templates
Custom Elements
HTML Imports
Using Web Components in Angular
Using Polymer elements