How to use ES6 standard with Babel.js
In the post “Coherent GT 2.0. is just around the corner,” we introduced you to the new major features of the upcoming Coherent GT 2.0. One of these features is the updated JS engine with full ES6 support. In this tutorial, we’ll give you more details about ES6, the main benefits of the new features, and we will tell you how to use ECMAScript 6 standard with Babel.js.
Introduction to ES6
ECMAScript 6, also known as ECMAScript 2015, is a significant update to the language since ES5 was standardized in 2009. The 6th edition’s syntax includes classes and modules, for/of loops, arrow functions, promises and much more (you can find the complete list here).
Main benefits of the new features:
1. Block scoped variables
Let keyword allows you to declare variables that are limited in scope to the block, statement or expression in which they are used. Unlike the var keyword, which defines a variable globally or locally to an entire function regardless of block scope.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function varTest() { var x = 1; if (true) { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } |
2. Classes
ES6 classes provide a much simpler and clearer syntax to create objects and deal with inheritance. ES6 syntax provides two ways to define a class: with class declarations or with class expressions.
Class declarations:
1 2 3 4 5 6 |
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } |
Class expressions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// unnamed var Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }; // named var Rectangle = class Rectangle { constructor(height, width) { this.height = height; this.width = width; } }; |
Body and method definitions: This is where you define class members, such as methods or constructors:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area); |
3. Promises
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
1 2 3 4 5 6 7 |
const myFirstPromise = new Promise((resolve, reject) => { // do something asynchronous which eventually calls either: // // resolve(someValue); // fulfilled // or // reject("failure reason"); // rejected }); |
4. Modules
ES6 provides a more advanced module importing/exporting pattern than the widely used CommonJS pattern. We can now import/export multiple named values.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// lib/math.js export function sum(x, y) { return x + y; } export var pi = 3.141593; // app.js import * as math from "lib/math"; alert("2π = " + math.sum(math.pi, math.pi)); // otherApp.js import {sum, pi} from "lib/math"; alert("2π = " + sum(pi, pi)); |
Some additional features include export default and export:
1 2 3 4 5 6 7 8 9 10 |
// lib/mathplusplus.js export * from "lib/math"; export var e = 2.71828182846; export default function(x) { return Math.log(x); } // app.js import ln, {pi, e} from "lib/mathplusplus"; alert("2π = " + ln(e)*pi*2); |
Note: More tutorials about ES6 will be coming later on.
What is Babel.js
Babel is essentially an ECMAScript 6 to ECMAScript 5 compiler; it fills the gaps between the new ECMАScript features and the current JavaScript implementations. Babel allows you to use ES6 features in your projects and then compiles ES5 for you to use in production.
Installing Babel
Prerequisites:
Node.js: since npm is used we need to have Node.js installed
package.json: You have to create your package.json file where all of your dependencies will be listed. You can do this by running the following command in the console:
1 |
npm init |
To create a blank package.json just simply press Enter all the way through.
Setup Babel
The most for ward way to use Babel is via the command line interface (‘CLI’). Developers recommend installing
Babel locally project by project. Just simply run:
1 |
npm install --save-dev babel-cli |
After installation finishes, your package.json file should look like this:
1 2 3 4 5 6 7 |
{ "name": "my-project", "version": "1.0.0", "devDependencies": { "babel-cli": "^6.0.0" } } |
Using Babel
Instead of running Babel directly from the command line, we will update the package.json file with new
“script.” Edit the “scripts” field to your package.json by putting the Babel command inside there as build.
1 2 3 4 5 6 7 8 9 10 |
{ "name": "my-project", "version": "1.0.0", "scripts": { "build": "babel src -d lib" }, "devDependencies": { "babel-cli": "^6.0.0" } } |
The Babel build command assumes you have src and lib folder. The src folder will hold the input you want to transpile, and the lib folder will contain the transpiler output.
Configuring Babel
Now Babel is installed, and we have to configure it. Create a .babelrc config file in your project root folder and enable the env preset plugin, which makes transforms for ES2015+. Install it with:
1 |
npm install babel-preset-env --save-dev |
To enable the preset plugin, you have to define it in .babelrc like this:
1 2 3 |
{ "presets": ["env"] } |
Now you can run Babel with the following command:
1 |
npm run build |
Example
In this sample we’ll see how to convert a simple class to ES5. Create a Rectangle.js file in the src folder including the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } } |
To build your ES5 file simply run:
1 |
npm run build |
In the lib directory, a new Rectangle.js file will appear, holding the ES5 Javascript code. This Rectangle.js is the file you would use in production. When you run this command, any existing files with the same name will be overwritten. You can place whole samples inside the src folder, and after running this command, the director y structures will be present in the output folder.
Note: If any files or folders are removed from src, they will remain inside the lib folder.
Useful links with more information