Skip to content

Latest commit

 

History

History
223 lines (170 loc) · 3.88 KB

21-ECMA.md

File metadata and controls

223 lines (170 loc) · 3.88 KB

Babel and ECMAScript

ECMA compatibility table

Babel-Node

  • babel-node app.js

Build to Node6

  • Build one file use babel index.js -o server.js
  • Build ES2015 + Stage-0 in src to dist folder use babel src -d dist --presets=es2015,stage-0 --plugins=transform-runtime
  • Run with babel-node use babel-node src/index.js --presets=es2015,stage-0 --plugins=transform-runtime
  • Inplace via Babel/Register require('babel-register')({presets: ['es2015', 'stage-0']}) and require('babel-polyfill')

Examples

Block-Scope

let a = 'foo';
const b = 'bar';

Template Strings

const foo = 42;
const output = `The value is: ${foo}`;

Destructing

const { foo, bar } = {
  foo: 'foo',
  bar: 'bar',
  foobar: 'foobar',
};
console.log(foo, bar);

Classes

class Bar {
  constructor(value) {
    this.value = value;
  }
}

class Foo extends Bar {
  constructor(value) {
    super(value);
    console.log(`Foo extends Bar with argument ${value} - ${this.value}`);
  }
}

const foo1 = new Foo('foo 1');
const foo2 = new Foo('foo 2');

Statics

class Foo extends Bar {
  static do = () => console.log('done');
  constructor() {
    super();
    console.log('Foo extends Bar');
  }
}

Foo.do();

Object-Literal Extentions

function getSomething(foo, bar, value) {
  return {
    foo,
    bar,
    value,
    ['foo' + make]: true,
    depreciate() {
      this.value -= 2500;
    },
  };
}

const something = getSomething('Foo', 'Bar', 40000);

console.log(something);
something.depreciate();
console.log(something.value);

Modules, Exports and Imports

export ...
import { A, B, C } from './module'

export default ...
import Module from './module'

Arrow Functions

const fn = value => `Hello World ${value}`;

Default Parameter

function myFunc(a = 'A', b = { bar: 'bar' }) {}

Rest Parameters

function(a, b, ...theArgs) {
  console.log(a, b, theArgs.length)
}

Spread Operator for Objects

const myObj = { foo: 'foo' };
const newObj = {
  ...myObj,
  foo: 'bar',
};
console.log(newObj);

Spread Operator for Arrays

const myArray = ['shoulders', 'knees'];
const myNewArray = ['head', ...myArray, 'and', 'toes'];
console.log(myNewArray);

Promises

Promise.resolve({});

Promise.reject(new Error('error...'));

new Promise((resolve, reject) => {
  resolve();
});

Promise.all([])
  .then(console.log)
  .catch(console.error);

Async and Await

function async doAsync(){
  return await domeAsync()
}

Generator Function

function* counter() {
  let index = 0;
  while (true) yield index++;
}

const gen = counter();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

for..of

Iterator pattern at the syntactic level

function* foo() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
  return 6;
}

for (const v of foo()) {
  console.log(v);
}