ES6 of the Week

This Week's Episode:

modules

Modules

  • JavaScript has not had a built-in module loader until ES6
  • The two main options up until now: CommonJS (using 'require', which Node implements, and AMD (Asynchronous Module Definition)
    • CommonJS - generally used server-side, optimized for synchronous loading
    • AMD - generally used client-side, optimized for asynchronous loading

ES6 Modules

  • Optimized for both synchronous and asynchronous loading - can be used on client or server
  • Static structure - because the compiler can tell what the imports/exports are, it can perform various performance optimizations
  • Supports cyclic dependencies
  • Note: Node does not yet have a native solution for this - after transpilation, we are still using CommonJS

Common Exports

/* export.js */

// you can export multiple values
export const foo = 'foo';

export function bar () {
    console.log('bar');
}

// you can also specify a default export
export default function baz () {
    console.log('baz');
}

Full list

export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // also var
export let name1 = …, name2 = …, …, nameN; // also var, const

export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;

Common Imports

// the default export can just be named
import baz from './exports.js';

// non-defaults can be enumerated in curly braces
import {foo, bar} from './exports.js';

// you can also import everything with a namespace
import * as myModule from './exports.js';

Full List

import defaultMember from "module-name";
import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";

ES6 of the Week - 9

By Tom Kelly

ES6 of the Week - 9

Modules

  • 1,639