Yakov Fain's Blog

My notes about everything in IT

Why writing JavaScript applications in TypeScript

with 2 comments

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.


Written by Yakov Fain

October 2, 2015 at 8:10 pm

Posted in Angular2, TypeScript

From Flex to Angular and Polymer

with 2 comments

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 stared 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 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 are 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).

As to tooling, we’re pretty happy with a combination of TypeScript, JSPM, and SystemJS. The entire app can be easily modularized. SystemJS loads modules of different formats (ES6, CommonJS, AMD). JSPM is a package manager that works with SystemJS well.

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

Currently A2 is in the 35th build of Alpha. There is 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 in 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 form 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 till January.

Our book “Learning Angular 2” 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.

Finally, there is a light at the end of the tunnel, namely Google’s Polymer. This library comes with a set of prefabricated UI components, but what’s more important, you can create your own Web components based on it.

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. Anyway,  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.

Written by Yakov Fain

August 23, 2015 at 2:11 pm

Posted in Angular2, flex, javascript

Java HashSet becomes a little faster

with 2 comments

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<nTests; i++){
		totalTime += populateHashSet(initialSize, loadFactor);					
	   System.out.println("With JRE " + System.getProperty("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){
		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; 
		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.

Written by Yakov Fain

August 18, 2015 at 3:41 am

Posted in java

A Toolbox of the Angular 2 Developer

with 10 comments

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.

* 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 is also a package manager but for application dependencies. Your application will need the Angular framework. Install it with Bower. Need a unit testing framework Jasmine? Install it with Bower.You can install literally any
JavaScript library or a framework with Bower.

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

* 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.

Written by Yakov Fain

July 4, 2015 at 11:47 am

Posted in Angular2, javascript

The private in TypeScript is kinda private

with 6 comments

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 descendents, 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.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.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. 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.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. Also, to ensure that the directory with generated JavaScript files doesn’t have files from previous compilation use the build automation tool like Gulp or Grunt with a clean task to remove old generated files on each compile.

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

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

Written by Yakov Fain

June 30, 2015 at 10:41 pm

Posted in javascript, TypeScript

Writing Technical Books 101

with 4 comments

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.

Written by Yakov Fain

June 27, 2015 at 3:40 pm

Posted in IT Career

ECMAScript 6 modules in the browser with Traceur

leave a comment »

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>
    <script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
    <script src="es6-module-loader.js"></script>

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

<script type="module">

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

         .then(function(module) {
             console.log("Shipping module Loaded ", module);


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



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:


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.

Written by Yakov Fain

May 30, 2015 at 3:26 pm

Posted in ES6


Get every new post delivered to your Inbox.

Join 180 other followers