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

Mod­ules have been around in javascript for a while now. The two com­pet­ing stan­dards for mod­ule dec­la­ra­tion have been the AMD and Com­monjs spec­i­fi­ca­tion. With the new ES6 specs, mod­ule def­i­n­i­tion and con­sump­tion is now part of the lan­guage itself. This arti­cle will be the first install­ment of our Learn­ing ES6 series. In this arti­cle, I am going to take some very sim­ple exam­ples to demon­strate the usage of ES6 modules.


Quite sim­i­lar to Com­monjs, ES6 lets you export and import objects, albeit it does so in slightly dif­fer­ent ways.

Exam­ple 1:

Using a sin­gle export at the end of your mod­ule file. This form of usage is called a named export because while export­ing you are defin­ing the name of the objects being exported.

foobar.js

function foo() { return 'foo'; }

function bar() { return 'bar'; }

export { foo, bar };

Notice how we use the new javascript object short­hand nota­tion on the last line when export­ing objects.

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

main.js

import {foo, bar} from 'foobar';
foo();
bar();

import * as lib from 'foobar';
lib.foo();
lib.bar();

Exam­ple 2

In another for­mat for using named exports, you can also export objects/function as and when you cre­ate them. I find this syn­tax a bit more con­ve­nient than the one we saw above.

foobar.js

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

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

Exam­ple 3

ES6 also has some­thing called as a default export. A file can have zero or 1 default export. For­tu­nately, you can use zero or many named exports in a file con­tain­ing default exports. For example

foobar.js

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

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

And here’s how you would con­sume it

main.js

// 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 mod­ule 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 cov­ers the ways in which you can use the new ES6 modules.


You may also like...