blogtech

EcmaScript 6: a modern Javascript Language

Javascript is one of the most important language in existence nowadays. Every browser has a built-in Javascript interpreter, NodeJs as a server-side scripting language  is becoming more and more popular, and now it is even possible to use Javascript to build desktop app (Chrome app), mobile app (Cordova/React Native).

The current version of Javascript is ES5 but it lacks of some basic languages feature like: Class, Module separating, Block-scope, etc…  That why ES6 was introduced as an upgrade to current ES5. This blog will cover some basic usage of ES6 and how to apply ES6 to your project

Setup ES6 enviroment

To setup ES6, I prefer to use Babel as the Javascript compiler and Webpack. So the first thing we need to do is install these 2 package

[code language=”bash”]
npm install –save-dev babel-loader babel-core babel-preset-es2015
npm install –g webpack
[/code]

Next we need to create Webpack config file webpack.config.js

[code language=”javascript”]
module.exports = {
entry: ‘./entry.js’, //This is link to the original file, change it
output: {
path: __dirname,
filename: ‘bundle.js’;, //This is name for the compiled file, change it
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: ‘babel-loader’}
]
}
};
[/code]

Next we need to create Babel config file .babelrc

[code language=”javascript”]
{‘presets’: [‘es2015’]}
[/code]

Finally we just need to execute the following command for Webpack to automatically compile our Javascript

[code language=”bash”]

webpack –watch

[/code]

Basic ES6 syntax

Constant

[code language=”javascript”]
const pi = 3.14
pi = 5 //error, cannot modify constant
[/code]

Block-scoped variable

[code language=”javascript”]
let x = 5;
{
let x = 5 //This is a new scope
}
x === 5 //This is the old scope
let x = 6 //Error, re-declared variable
[/code]

Arrow function

[code language=”javascript”]
odds = evens.map(value => value + 1)
//equal to
odds = evens.map(function(value) { return value + 1; });
[/code]

Default parameter

[code language=”javascript”]
function foo(x, y=7, z=42) { return x + y + z }
foo(1) === 50
[/code]

Template string

[code language=”javascript”]
var name = ‘Bob’;
template = `Hello ${name}`; //This is equal to ‘Hello Bob’
[/code]

Module

[code language=”javascript”]
//file lib/math.js
export function sum(x, y) { return x + y }
export var pi = 3.14
//file app.js
import {sum, pi} from  ‘lib/math’
[/code]

Class

[code language=”javascript”]
class Shape {
constructor(x, y){
this.x = x; //This is class attribute
this.y = y; //This is class attribute
}

move(){ //This is a class method
this.x = this.x + 1;
this.y = this.y  + 1;
}
}
[/code]

Above is some of the usages and how to setup ES6 enviroment. You can find more usage and example from Babel page. Hope you find this is helpful.

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です