ECMAScript Harmony – Compile ES6 code to ES5 using Traceur/Babel

ECMAScript Edition 6 (ES6) comes with lot of features such as classes, generators, destructuring, modules and much more. Currently ES6 code is not yet implemented/supported in all browsers and JS engines, you might wanna look here. Using Firefox and chrome(latest) developer tools you can test features like arrow functions etc. for chrome you will also need to enable chrome harmony flag. chrome://flags/#enable-javascript-harmony.

It might be bit early but you wanna to use latest ES6 features and here you will need a compiler that compiles your ES6 code down to regular Javascript that could run in browsers. currently we have two most famous compilers Traceur and Babel for this purpose.

Traceur

You can try Traceur in several ways:

  • Include Traceur in a Web page and it will compile ES6 code on the fly.
  • Or use node to compile ES6 to ES5 offline and include the result in Web pages or just run the result in node.

For browser you can include following script and it will convert automatically.

In above example first file included above is the traceur compiler; next comes a small file of JS to apply the compiler to the Web page. Traceur itself written in ES6. so my simple example manipulate the array using high order function .map  that takes arrows function as callback.

You can also import ES6 modules

Other way is using offline compilation. for that you need node installed. Traceur includes a shell script traceur to compile ES6 code to ES5/Regular JavaScript.

We can test the module.js we just compiled like:

This runtime file contains polyfills as well as helper functions which reduce the generated code size. you can find more about traceur here.

Babel

Babel is another compiler for EcmaScript6.

You will need to include following files to your web page.

  • node_modules/babel-core/browser.js
  • node_modules/es6-module-loader/dist/es6-module-loader.js

Following is example to import ES6 module

Let’s setup development envirnmnet and start using ES6 using Babel in your applications. you’ll need to install following presets and plugins

babel-preset-es2015 is for ES6 and babel-preset-stage-0 is for ES7 experimental features, this is not required in our case, it may be good idea to have it.

Simple express application written using ES6 could be:

Above command will transpile ES6 code from express.js to out/express.js. so that will normal JavaScript which can run in ES5 or less supported environments.

Following is the output:

Also it is possible to compile whole directory containing ES6 code files using following way:

 

  • Marcio Mauricio

    Uncaught SyntaxError: Unexpected token import