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.

Java HashSet becomes a little faster

I was experimenting with Java HashSet, which is a pretty expensive collection to create, but it has a benefit of the O(1) performance while finding the elements from this collection. Based on my experiments performance of HashSet is improved over the last year.

I’ve written a small benchmark comparing the performance of the one year old JRE 1.8.0_05 with the latest 1.8.0_60. In my tests I’m creating a HashSet containing 100000 objects. The object looks like this:

import java.math.BigDecimal;

public class MyObject {

	public String s1 = "aaaaaaaaaaaaa";
	public Double d1 = 222222222222.22;
	public BigDecimal b1 = new BigDecimal(1.54);
	public int i1;
	
	public String s2 = "aaaaaaaaaaaaa&amp";
	public Double d2 = 222222222222.22;
	public BigDecimal b2 = new BigDecimal(1.54);
	public int i2;
	
	public String s3 = "aaaaaaaaaaaaa";
	public Double d3 = 222222222222.22;
	public BigDecimal b3 = new BigDecimal(1.54);
	public int i3;	
}

My test program runs two test loops. First, I preallocate the memory for the HashSet capable of storing 133000 object with the load factor 0.75. In the second loop I create the HashSet with the default initial size 16 and the same load factor. The load factor 0.75 causes the HashSet to grow if the number of elements becomes greater than 75% of the initial capacity. I was expecting the first loop to perform a little better because there is no need to do additional memory allocations. Here’s the test program:

import java.time.Duration;
import java.time.LocalTime;
import java.util.HashSet;

public class Main {

	static int iterations = 100000;
	static float loadFactor=0.75f;
	static int initialSize = (int)Math.round(iterations/loadFactor);
	
	public static void main(String[] args) {
       
	   int nTests = 10;
	   long totalTime = 0; 
	   
	   // HashSet with large initial size
	   for (int i=0; i&amp;lt;nTests; i++){
		totalTime += populateHashSet(initialSize, loadFactor);					
	   }
	   
	   System.out.println("With JRE &amp;quot; + System.getProperty(&amp;quot;java.version") + " the average time (in milis) to populate the HashSet of initial size " + initialSize + " is "+ totalTime/nTests);
	  
	   
	   // HashSet with default initial size
	   initialSize = 16;  // default for HandSet
	   totalTime = 0; 
	   
	   for (int i=0; i < nTests; i++){
		totalTime += populateHashSet(initialSize, loadFactor);					
	   }
	   
	   System.out.println("With JRE &amp;quot; + System.getProperty("java.version") + " the average time (in milis) to populate the HashSet of initial size " + initialSize + " is "+ totalTime/nTests);
	}
	

	static long populateHashSet(int size, float loadFactor){
     
		System.gc();
		
		HashSet&amp<MyObject> hashSet = new HashSet<>(initialSize, loadFactor);
		
			LocalTime before = LocalTime.now(); 
			
	
			for (int i =0; i < iterations; i++){
				MyObject obj = new MyObject();
				obj.i1 = i*2; 
				hashSet.add(obj);
			}
		
		LocalTime after = LocalTime.now();
		
       return Duration.between(before, after).toMillis();		
				
	}
}

Running this program in two different JREs shows the following results:

With JRE 1.8.0_05 the average time (in milis) to populate the HashSet of initial size 133333 is 167
With JRE 1.8.0_05 the average time (in milis) to populate the HashSet of initial size 16 is 152

With JRE 1.8.0_60 the average time (in milis) to populate the HashSet of initial size 133333 is 153
With JRE 1.8.0_60 the average time (in milis) to populate the HashSet of initial size 16 is 141

My test shows that the HashSet in JRE 1.8.0_60 gets populated about 10% faster than with JRE 1.8.0_05. If your application works with large HashSets you should upgrade your JRE.

What I can’t explain is why the numbers with default initial size are better than with the HashSet with pre-allocated memory.

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.

The private in TypeScript is kinda private

TypeScript includes the keywords public, protected, and private to control access to the members of a class such as properties or methods. Public class members are visible from within and outside the class, protected are visible form the class and its descendants, and private are visible from within the class only. But being a superset of JavaScript, which doesn’t support the private keyword, using private members in TypeScript is not what you may expect.

Let’s look at the example of the class Person, which has three public and one private property.

class Person {
    public firstName: string;
    public lastName: string;
    public age: number;
    private ssn: string;

    constructor(firstName:string, lastName: string, age: number, ssn: string) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.ssn = ssn;
    }
}

var p = new Person("John", "Smith", 29, "123-90-4567");

console.log("Last name: " + p.lastName + " SSN: " + p.ssn);

The TypeScript compiler properly reports an error at the last line where I tried to access the private variable ssn. Here’s the error:

“Error:(17, 53) TS2341: Property ‘ssn’ is private and only accessible within class ‘Person’.”

But this should have been marked as a warning, because the TypeScript compiler generates the JavaScript code anyway, which looks like this:

var Person = (function () {
    function Person(firstName, lastName, age, ssn) {
        this.firstName = firstName;
        this.lastName;
        this.age = age;
        this.ssn = ssn;
    }
    return Person;
})();

var p = new Person("John", "Smith", 29, "123-90-4567");
console.log("Last name: " + p.lastName + " SSN: " + p.ssn);

To see the code generation in action, visit the TypeScript Playground at http://bit.ly/1GKUeV0. As you see all traces of privacy have been removed, the property ssn has been exposed to the outside world as every other Property on the Person object.

Moreover, there is an easy workaround for accessing the “private” ssn even in TypeScript by casting this property to the type any:

console.log("Last name: " + p.lastName + " SSN: " + (p as any).ssn);

There must be some reason why creators of the TypeScript compiler didn’t turn the class Person into the JavaScript closure that would actually make ssn private, for example:

var Person = (function () {
    var _ssn;
    
    function Person(firstName, lastName, age, ssn) {
      
        this.firstName = firstName;
        this.lastName;
        this.age = age;
        _ssn = ssn;
    }
    return Person;
})();

But it is what it is. So when you use the private keyword in TypeScript, keep in mind that it just suggests you to be nice and not access it directly, but write public getter and setter methods instead.

Let’s extend the class Person like this:

class Employee extends Person{
    ssn: number;
}

TypeScript’s compiler will give you an error:

Error:(17, 53) TS2341: Property ‘ssn’ is private and only accessible within class ‘Person’.

But it’ll still generate the JavaScript code unless you add a compiler option –noEmitOnError to not generate JavaScript until all TypeScript syntax errors are fixed.

Having said that, I still like TypeScript. Developing in TypeScript is clearly more productive than in JavaScript. For more TypeScript articles go here.

P.S. IMO, protected variables are useless in any object–oriented language.

Writing Technical Books 101

So you’re an expert programmer and decided to write a technical book? Think twice. Why do you want to write it? These are possible answers:

1. All these years I’ve been using the IT knowledge so generously shared by other people, and it’s time to give back to the community. Great answer! But does it have to be a book? Have you tried answering other people’s questions on StackOverflow? Have you’ve written a couple of dozen of blogs that people read and like? If the answer is no to any of these questions, start there because writing a book is harder.

2. I want to become a published author. This will give me better recognition in the industry and will look good on my resume. I hear you. This is true unless the book you’ll write will suck. If your book will get mostly negative reviews, you’ll remove it from your resume. But you can’t remove it from the Internet, can you?

3. I want to earn some extra cash in the form of royalties. This is the worst possible reason for writing a technical book, because the money is not there. This is not to say that there are no people making a good living just by writing technical books, but the chances that you’ll become one of them are similar to a fiction book writer becoming the next J.K. Rolling.

I’ll give you some of my numbers. My most financially successful technical book so far is the first edition of Java 24-Hour trainer, which brought me $40K in royalties over four years. Apparently the publisher considered this book a financial success as well, because they offered me to write a second edition of this book. So consider making $10K a year in royalties a good result for your book.

Still want to write your book? Now let me ask you some questions.

1. Do you have a discipline to write every day to meet the schedule? You may be surprised, but the publisher will request your manuscripts to be submitted by the certain dates. The editors will be contacting you asking about the status of your chapters, because they also have their deadlines to meet.

The most common mistake the rookie writers can make is not writing daily. You can’t just live your regular life and write something once in a while. You need to think about your book all the time. Missing a day of writing is a slippery slope, which will require more time and discipline to continue where you left off.

2. Are you ready to listening to valid complaints of your spouse/girlfried/boyfriend that you’re stealing the time from your family, kids, and other fun things you could have done together? And they are right. You are going to be stealing their time.

3. Are you ready to seeing your book illegally distributed for free on all these torrent repos as soon as it hits the book stores? How come? After all this dedication and time spent to make the world a better place they what your content for free? Yes they do. Have you ever downloaded a movie or a song for free without paying for it? You are the same as all these people downloading your book for free. No complains here, but try to turn negative into positive. These free downloads make your name recognizable in the industry, which may be a good thing when negotiating salary or offering training classes.

4. Are you ready to be called an idiot for a typo in the code samples? Actually, I need to give a compliment to my American readers here. They are more polite than the rest of the world , and in most cases will try to give you a constructive criticism.

Still want to write after reading all this? I’m really happy for you! Because I also continue writing despite all these cons. After every completed book project I say to myself, “Never again”, and then start working on a new book.

To summarize, these are some rules I can share with you based on my book writing experience.

1. Never try to make the draft of your chapter perfect before submitting it to the publisher. They’ll modify the text anyway unless you have a college degree in writing, which most software developers don’t. Push the chapter our of the door quickly. Fail fast! Get the feedback as soon as possible to have more time for fixing it.

2. Write every day. Even if it’s just one or two paragraphs. The process has to be continuous. Even the writer-alchoholic Henry Chinaski forced himself to write every day. So booze, gym, or other time-consuming hobbies are not excuses for not writing daily.

3. Don’t write in MS Word or a similar word processor. Use any plain text editor and the Asciidoc markup language with future generation of the code in HTML/PDF/EPUB/MOBI formats. I’m writing my third book with Asciidoc and am pretty happy with it.

4. Store all your drafts on GitHub even if you’re the only author of your book. GitHub also has a very nice feature called GitHib Pages that allows to publish your drafts online. For example, this is how my free book Java For Kids looks at GitHub pages. If you don’t want to make your drafts publicly available, either buy a private repository on GitHub
or create it for free on BitBucket.

P.S. Most likely, you’ll find grammar errors in the text of this blog. It’s OK. I need to push it out the door ASAP to get your feedback sooner. Please leave comments and I’ll fix the mistakes later.

P.S.S. I’ve stolen the time allocated for writing a chapter for my next book on Angular 2 and wrote this blog instead. Stupid me.

ECMAScript 6 modules in the browser with Traceur

ECMAScript 6 standardizes the syntax of modules. A module is simply a Javascript file that you can load either on the application startup or lazily on the as-needed basis. ES6 modules give you complete control on what code to export to the external scripts and what to keep private to the module. Prepend a variable, a function, or a class definition with the keyword export, and all other scripts in your project can import the module’s API using the import keyword. For details of using modules, read this great post by Dr. Axel Rauschmayer.

But the ECMAScript 6 specification doesn’t define module loaders, which can be used both in the browsers and in the standalone JavaScript engines. Eventually all Web browsers will support the System object that knows how to import modules, but meanwhile you can use the polyfill ES6 Module Loader or, if you want to go fancy and ensure that your AMD and/or CommonJS modules are also loaded in a standardized fashion, go with the universal system module loader called SystemJS.

Since ES6 syntax is not fully supported by any of the modern browsers, you’d need to transpile the code from ES6 to ES5 using one of the transpilers such as Traceur or Babel. In this blog I’ll show you how to dynamically load ES6 modules in the Web browsers with auto-transpiling using Traceur. To run this example on your computer you’ll need to have node.js with npm installed.

First, you need to download and install es6-module loader in any directory by running the following npm command:

npm install es6-module-loader

Then create an application folder and copy the file es6-module-loader.js there (this is a minimized version of the loader that was downloaded by npm). Our sample application will have two additional files: moduleLoader.html and shipping.js. For simplicity I’ll keep all these files in the same folder.

Imagine that we develop an online store with a large code base. To avoid creating a monolithic application, we’ve split it into loadable modules. In particular, the module that handles shipping should be loaded only if the user clicks the Shipping button. Here’s the code of our “huge” shipping module:

export function ship() {
    console.log("Shipping products...");
}

function calculateShippingCost(){
    console.log("Calculating shipping cost");
}

Since I used the export keyword only in front of the ship() function, the function calculateShipptingCost() will remain private for the module and won’t be accessible from the outside. No need to implement the module design pattern with immediately-invoked function expressions, and no need to use a third-party framework like RequireJS.

The file moduleLoader.html includes a script that loads and uses the shipping module. In this example I use Traceur for the on-the-fly transpiling of the ES6 code to ES5 so it can run in any browser. Here’s the file moduleLoader.html:

<!DOCTYPE html>
<html>
<head>
    <title>modules.html</title>
    <script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
    <script src="es6-module-loader.js"></script>
</head>
<body>

  <button id="shippingBtn">Load the Shipping Module</button>

<script type="module">

let btn = document.querySelector('#shippingBtn');
btn.addEventListener('click', () =>{

     System.import('shipping')
         .then(function(module) {
             console.log("Shipping module Loaded ", module);

             module.ship();

             module.calculateShippingCost();  // will throw an error
         })
         .catch(function(err){
             console.log("In error handler", err);
         });
});

</script>

</body>
</html>

In Line 5 we load the Traceur for transpiling. In line 6 we load es6-module-loader to support the System object that will load the shipping module using the import() call when the user clicks on the button. The import returns the ES6 Promise object, and when the module is loaded, the function specified in then() will be executed. In case of an error the control goes to the function catch().

Inside the then() we print the message on the console and invoke the exported function ship(). After that we try to invoke the module’s function calculateShippingCost(), which will result in error because this function was not exported and remained private.

NOTE: When you have the inline script in the HTML file, you should use type="module" to make sure that the Traceur transpiles it to ES5. Without it, the browser that don’t support the let keyword (line 14) and arrow functions (line 15) would complain.

To see this code in action you need to serve it using some Web server. I use WebStorm IDE for development, which comes with embedded Web server. Lets run moduleLoader.html in Google Chrome and open Chrome Developer Tools. This is my Chrome browser looks after I clicked on the button Load the Shipping Module:

7

Look at the XHR tab in the middle of the window. The HTML page has loaded shipping.js after I clicked on the button. The size of this file is small and making an additional network call to get it seems like an overkill. But if the application consists of 10 modules 500KB each, modularization with lazy loading makes sense.

At the bottom, on the console tab you see the message from the script in moduleLoader that the shipping module was loaded. Then it calls the function from ship() from the shipping module, and generates an error trying to call the function calculateShippingCost() as expected.

In the real-world projects you should integrate transpiling in the project build, but I just wanted to illustrate the ease of the transpiling in the Web browser without any additional preparations. Transpilers allow you to start programming in ECMAScript today.

Categories ES6

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

Be careful with authorization servers

These days people are accustomed to logging in to various Web sites using third-party authorization services. Do you want to login using your Facebook or Twitter account? In technical terms, this means that you are being offered to delegate the process of authorization to a third-party service offered by Facebook, Twitter or other big guys.

You’re sick and tired of creating and remembering dozens of IDs/passwords for all theses online services. Please, please login me quickly using whatever service you want. Most of such services are implemented with OAuth protocol, which allows to use the user’s account on some other servers to authorize you for accessing someone’s Web site. The good part is that OAuth servers do not reveal your id/password, but perform the authorization returning a special encoded token that will be used as you temporary passcard. The access to your Facebook or Twitter account will be limited.

1

The concept of giving a limited access to a resource is easily explained to rich people, who have these fancy cars with the ignition key that includes a removable small key so you can lock the glove compartment (full of diamonds) while giving a large key to a valet parking attendant. If you’re not that rich yet, take a look at this image:

2

Say you are visiting a Web site xyz.com, with offers you login with one of your social networks’ account. Creators of xyz.com must reveal what exactly they will be able to do with your credentials. It’s great that they won’t be able to login to your Twitter account, but will they be able to tweet on your behalf or start following people? Always read text on such login windows before clicking on that easy-to-login button.

I’ll give you a couple of examples. Here’s how Right Relevance offers you to login to their site:

3

With all my respect to Right Relevance for their good technical content, I wouldn’t want them to post tweets for me. Thanks, but no thanks.

Here’s another one. In April I was speaking on OAuth authorization at a Java conference in Moscow, Russia. In the evening I went to see a show in a popular theatre, which offered a free Wi-Fi hotspot. Nice! When I tried to connect to this spot from my phone I got this message:

4

Thank you, Hot Wi-Fi, but you’re not that hot for letting you tweet for me. Besides, it’s not polite to browse the Internet while watching a play with famous actors.

One more example, and I’ll let you go. This morning I’ve received an email that someone I know sent me a private message via a social network called Zorpia. I don’t know where are these people learning about such services, really. Anyway, you don’t have to be a rocket scientist to guess what Zorpia wants for showing me that private massage:

5

No, for some reason I don’t want you to manage my contacts. I frequently get emails that start like this: “John Smith is updating his contact information at the social network xxx.com and asks you to login and update your cell phone number there”. Needless to say that xxx.com starts with offering me to login with one of the popular OAuth servers, and I’d say “No”.

Don’t blame the OAuth protocol, which has all provisions for restricting the access for these third-party applications. There is a special scope parameter that allows to specify what a third-party app can do on your behalf. For example, here’s the description of the scope parameters for the developers who want to delegate authorization to Google’s OAuth servers.

Here’s my message to you: “Think twice before letting some Web application to delegate the authorization process to someone else.” Read the fine print!