ES6 Modules

This is the part of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements.

In this blog we focus on the Module features introduced in ES6 which are comprised of Imports and Exports.

Syntax #

It’s quite simple with only import and export keywords.

Modules #

While modules are not a new thing for many javascript developers with the rise of Asynchronous Module Definition (AMD) and CommonJS (CJS), ES6 offers devs a standard way of importing and exporting modules to have more modular code. Modules allows for runtime behaviour defined by a host-defined default loader. Modules are also async in nature in that no code runs before the request modules are available and processed.

Export #

We will base off the examples off this base code for exports:

function foo() {
    return "I am foo";
}
 
function bar(a, b) {
    return a + b;
}

var fizz = "buzz";

Variable:

export fizz

Function:

export {foo, bar}

Renamed functions:

export {foo as f, bar as b}

If you want to export the imported value you can use the default keyword:

import math from "lib/my-math-module";
math.PI = 3.14;
export default math; // exports lib/my-math-module

Everything:

export * from "lib/my-math-module";

Import #

Basic Syntax:

import myModule from "my-module.js";
import "my-module.js" as myModule; // equivalent

One variable:

import {myMember} from "my-module.js";

Multiple variables:

import {foo, bar} from "my-module.js";

Mixed imports:

import MyModule, {foo, bar} from "my-module.js";
alert(MyModule.foo === foo); // true

Renaming imports:

import {annoyingJavaClassName as className} from "my-module.js";
alert(className); // annoyingJavaClassName

Everything:

import * as math from "lib/my-math-module";
alert("time= " + math.abs(10.17));

In Practice #

As I mentioned, its not an entirely new thing for anyone who has done a large scale javascript project. This does allow developers to have a standard way of defining modular approaches to organizing code and keeping it simple (stupid).

 
5
Kudos
 
5
Kudos

Now read this

React Rally 2016 Recap

I recently attended the React Rally conference in Salt Lake City, UT. The conference was about the front end server and client framework React, created by Facebook. Speakers covered topics such as Redux, Relay, RethinkDB, Async and of... Continue →