-
Notifications
You must be signed in to change notification settings - Fork 2
ES6 (ES2015) Transpilation
The final ES6 standard was approved in June 2015. While most modern browsers have decent support for it some like IE 11 and FF 43 lack some features. (I'm kidding, IE11 doesn't implement ANY of the new features).
We are currently using BabelJS to compile ES2015 code to ES5. Babel is a transpiler that allows us to pick which features of the ES2015 and ES2016 standards we wish to implement in our code, and then converts it to ES5 code that all major browsers can parse and understand. This allows us to write code that's easier to read, but can still be understood by legacy browsers.
You'll generally want to have gulp running the watch task in the background so that you have active transpilation. Read more about setting gulp
For those on windows a good recommendation is using ConEmu, and defining a default workspace that is always running gulp watch in the background for you.
For those on Mac http://www.iterm2.com/
#####Configuration
The transpiler is configured to use the "es2015" and "stage0" presets:
#####IIFE
There are a couple of ways to do this:
(() => {
//Code
//I like this one because the result after the babel transpilation
//is the same as we did it before
//(function(){
//
//})();
})();or
{
//Code here
//This one is also cool but the only thing I don't like
//is that this one is translated by babel as:
//{
// (function(){
// //Code
// })();
//}
}#####Arrow Functions and Lexical "this"
startUpdateInterval: function () {
this.interval = setInterval(function () {
this.forceUpdate();
}.bind(this), 1000);
},
Turns into
startUpdateInterval: function () {
this.interval = setInterval(() => {
this.forceUpdate();
}, 1000);
},
#####String Interpolation (yay!)
var myString = `Today's temp is ${mockService.getTemp()}, great isn't it?`;
var multipleLines =
`String templates even "unescaped string literals"
and line breaks. Cool, huh?`
#####Improved Parameters
We usually do this:
function myFunction(x, y)
{
x = x || 'default-value';
y = y || 1;
}
Now we just do this:
function myFunction(x = 'default-value', y=1)
{
}
#####Better Iteration
Remember this?
for (var name in collection) {
if (collection.hasOwnProperty(name)) {
//write your code here
}
}
This looks better:
for (var name of collection) {
//code here
}
The downside is that we now have a ton of ways to iterate and can be confusing:
- for
- for...in
- for...of
- Array.prototype.forEach
(just avoid using for...in, it's not guaranteed to enumerate the collection in order, and it will include members inherited from the prototype)
#####More Readings
Check out these additional guides: