ES6 - Modules

Datetime:2016-08-23 01:03:58          Topic: ECMAScript           Share

At the core of modularity developers need a module system — a way to spread their work across numerous files and directories with access to each other. Without support for modules natively in ECMAScript there has been a community created effort to implement work-arounds — CommonJS and AMD being the most prevelant as

they both have communities that rally around them, but are incompatible with each other. The good news is ES6, ( TC39 group ) has finalized a module syntax which developers can greatly benefit from using the best from both worlds.

  • The goal of modules in ES6 is to keep both CommonJS and AMD user happy with a single format and borrows the best from both worlds
    • ES6 modules will have a compact syntax with a preference for a single exports ( such as CommonJS )
    • direct support for asynchronous and configurable module loading is supported
  • There are two types of exports, named exports and default exports
    • named exports can be used to export multiple things using the keyword export
    • default exports used to export a default single value
  • To import functions, objects and primitives that have been exported from an external module use the import statement
    • you may import an entire modules contents, a single member or multiple members in a module

A convenient way to specify named exports as below:

// lib.js
// -------
export const quux = Math.sqrt( 2 ); // => exports a constant
export function multiply( x, y ) {
  return x * y;
} // => exports a function


export function addContact( id, callback ) {
  callback();
} // => exports a function

export function refreshContact() {
  alert( `Hello ES6 Modules` );
} // => exports a function

And of course import them into another file:

// main.js
// -------
import quux from 'lib';
import { multiply, addContact, refreshContact } from 'lib';

console.log( quux ); // => 1.4142135623730951
console.log( multiply(10, 10); // => 1000
console.log(addContact(1, refreshContact)); // => alerts `Hello ES6 Modules`
// app.js
// ------
// import the whole module
import * as lib from 'lib'

console.log( lib.quux ); // => 1.4142135623730951
console.log( lib.refreshContact() ); // => alerts `Hello ES6 Modules`

Another technique in a module, we could use the following:

const quatro = 10 * 10 * 10 * 10;
export { quatro };

default exports is simple one module that you want to export as the default ( like CommonJS ) and it turns out you can use default exports and named exports both in your module. There is alot more on modules in ES6 including script tags, using promises and module loading which is an API that allows you to programmatically work with modules and configure module loading.





About List