require('babel-core/register');
require('./es6code');
// To run this file, do
// `node index.js`
es6code.js
import path from 'path';
class car {
startEngine() {
console.log('Ignition on');
}
}
Iteration
for...in: Iterate over property name, in arbitrary order (because property doesn't have order)
for (let prop in obj) {
// Check, in case prototype has customized properties
if (obj.hasOwnProperty(prop) {
// ...
}
}
// when using in array, it iterates on index
// Don't use this
for (let index in arr) {
}
// use Object.keys
Object.keys(obj).forEach(function (key, index) {
console.log(obj[key]);
}
// underscore
_.each(obj, function (value, key) {
});
ES6: Iterate over values: for .. of
for (let value of arr) {
}
// use forEach
arr.forEach(function (element, index) {
console.log(element);
});
// underscore
_.each(arr, function (element, index) {
});
CommonJS Modules: The dominant implementation of this standard is in Node.js (Node.js modules have a few features that go beyond CommonJS). Characteristics:
Compact syntax
Designed for synchronous loading
Main use: server
Asynchronous Module Definition (AMD): The most popular implementation of this standard is RequireJS. Characteristics:
Slightly more complicated syntax, enabling AMD to work without eval() (or a compilation step).
Designed for asynchronous loading
Main use: browsers
ES6
Declarative syntax (for importing and exporting)
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
// import
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
// import whole module
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
// import from node package
import fs from 'fs';
Default exports If you want to export only a single function, you have to use export default then you can do import a from 'MyClass'
export default function () { ··· } // no semicolon!
//------ main1.js ------
import myFunc from 'myFunc';
myFunc();
// class
//------ MyClass.js ------
export default class MyClass { ··· } // no semicolon!
// or
export { MyClass };
//------ main2.js ------
import {MyClass} from 'MyClass';
let inst = new MyClass();
Programmatic loader API: to configure how modules are loaded and to conditionally load modules