Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Using es6 modules with simple examples

Modules have been around in javascript for a while now. The two competing standards for module declaration have been the AMD and Commonjs specification. With the new ES6 specs, module definition and consumption is now part of the language itself. This article will be the first installment of our Learning ES6 series. In this article, I am going to take some very simple examples to demonstrate the usage of ES6 modules.

Quite similar to Commonjs, ES6 lets you export and import objects, albeit it does so in slightly different ways.

Example 1:

Using a single export at the end of your module file. This form of usage is called a named export because while exporting you are defining the name of the objects being exported.


function foo() { return 'foo'; }

function bar() { return 'bar'; }

export { foo, bar };

Notice how we use the new javascript object shorthand notation on the last line when exporting objects.

You can use the exported object from another file as follows.


import {foo, bar} from 'foobar';

import * as lib from 'foobar';;;

Example 2

In another format for using named exports, you can also export objects/function as and when you create them. I find this syntax a bit more convenient than the one we saw above.


export function foo() { return 'foo'; }

export function bar() { return 'bar'; }

Example 3

ES6 also has something called as a default export. A file can have zero or 1 default export. Fortunately, you can use zero or many named exports in a file containing default exports. For example


export default function foo() {
  return 'default foo';

export function bar() { return 'bar'; };

And here’s how you would consume it


// These will only get you foo
import mylib from 'foobar';
import {default as mylib} from 'foobar';

// This will get you both foo and bar
import mylib, {bar} from 'foobar';

Notice how in the above code, you were able to use the name ‘mylib’ instead of ‘foo’. Thats because foo was the default export in your module so you didn’t have to pluck it out of the exported object the way you had to do it if you only had named exported objects.

And that pretty much covers the ways in which you can use the new ES6 modules.

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...