A ES2015 Tutorial with Babel & Gulp

babel (1)

What is Babel?

Basically, Babel is a ECMAScript 6 to ECMACScript 5 compiler. This tool allows to use ES6 features in our projects. The process is simple, firstly, you should learn about new standard, such as let and const vars, arrow functions, classes, template string, default values and modules. Secondly, prepare a task with gulp and gulp-babel (see more later) and finally use other plugins such as  browserSync, plumber and concat.

Installation

git clone https://github.com/AFelipeTrujillo/A.ECMAScript.6.Tutorial.With.Babel.git
cd A.ECMAScript.6.Tutorial.With.Babel
npm install
gulp

ES6 Features

The new standard has a lot new features, in this post we are going to examine some of them. I addition, I am going to use GulpJS and Babel compiler in order to convert ES6 to ES5 syntax. Because a few browsers do not support ES6 yet, so it is necessary to keep the old standard.

Let and Const vars

With new standard, we can declare variables with let instead of var. Next code generates an error, because x is defined into IF block so it is inaccessible in others scopes.

ES6 Code:

(
    function(){
        console.log(x);
        if(true){
            let x = 'Hello Let !';
        }
        console.log(x);     
    }
)();

Compiled Code:

'use strict';

(function () {
    console.log(x);
    if (true) {
        var _x = 'Hello Let !';
    }
    console.log(x);
})();

Automatically, Babel puts ‘use strict’. I always forget it

Also, we can create constant variables, with reserved word const which you can only read in time execution and cannot modify. Let’s do it.

(
    function(){
        const PI = 3.15;
        PI = 2;     
    }
)();
scripts.js: "PI" is read-only

Arrow Functions

This feature help us in create code clearer and cleaner than the past. Next function takes two arguments (numbers) and add them.

ES6 Code:

let sum = (x,y) => x + y;

Compiled Code:

var sum = function sum(x, y) {
    return x + y;
};

Other example:

ES6 Code

var a = [
    "Hydrogen",
    "Helium",
    "Lithium",
    "Beryl­lium"
];

var aLength = a.map(s => s.length)

Compiled Code:

var a = ["Hydrogen", "Helium", "Lithium", "Beryl­lium"];

var aLength = a.map(function (s) {
    return s.length;
});

Find out more: Arrow Functions By Mozilla

Classes

With ES6, we can use classes almost the same to ES5 construct functions. Also, we will be able to use inheritance with extends.

class Vehicle
{
    constructor(owner,numDoors,numTires){
        this.owner = owner;
        this.numDoors = numDoors;
        this.numTires = numTires;       
    }

    render() {
        return `The ${this.owner}'s vehicle has ${this.numDoors} door(s) and ${this.numTires} tires`;
    }
}

class Car extends Vehicle
{
    constructor(owner,numDoors,numTires,color,price){
        super(owner,numDoors,numTires);
        this.color = color;
        this.price = price;
    }

    render(){
        return `${super.render()}. Also it is ${this.color} and its cost is USD ${this.price}`;
    }
}

class Lorry extends Vehicle
{
    constructor(owner,numDoors,numTires,lorryload){
        super(owner,numDoors,numTires);
        this.lorryload = lorryload;
    }

    render(){
        return `${super.render()}. Also it can load ${this.lorryload} tons`;
    }
}

Test Code:

var c = new Car('Andres',4,4,'yellow',4000);
c.render();

Template Strings

With ES6, we can interpolate strings much simpler and better. Look the next example:

ES6 Code:

let h = 'Hi';
let w = 'World!';

console.log(`I just wanna say ${h} ${w}`);

Compiled Code:

'use strict';

var h = 'Hi';
var w = 'World!';

console.log('I just wanna say ' + h + ' ' + w);

Destructuring

Now, we can get new ways to assign values to Array and Objects.

ES6 Code:

//Ex #1
let [a,b] = ['Javascript','Rocks']

//Ex #2
let hero = {name : 'Han', lastname : 'Solo'}
var { firstName, lastName } = hero;

//Ex #3
let fn = () => {
    return ['Dark','Vader']
}

let sith = fn();

Compiled Code:

'use strict';

var a = 'Javascript';
var b = 'Rocks';


var hero = { name: 'Han', lasname: 'Solo' };
var firstName = hero.firstName;
var lastName = hero.lastName;


var fn = function fn() {
    return ['Dark', 'Vader'];
};

var sith = fn();

Default Values

This feature will help you to create function easier. With ECMAScript 6, we can define a default var in params function. For example:

ES6 Code:

let mul = (x, y = 1) => x * y;

Compiled Code:

"use strict";

var mul = function mul(x) {
 var y = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
 return x * y;
};

Find out more: http://es6-features.org/

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s