Be the first user to complete this post
|
Add to List |
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.
- Part 1: Getting started with ES6 modules - THIS ARTICLE
- Part 2: Getting started with ES6 iterators and iterables
- Part 3: ES6 iterators and iterables - creating custom iterators
- Part 4: Getting started with ES6 generator functions
- Part 5: Generators and Yield in ES6
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.
foobar.js
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.
main.js
import {foo, bar} from 'foobar';
foo();
bar();
import * as lib from 'foobar';
lib.foo();
lib.bar();
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. foobar.js
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
foobar.js
export default function foo() {
return 'default foo';
};
export function bar() { return 'bar'; };
And here’s how you would consume 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 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.
Also Read:
- Understanding callbacks in javascript
- pseudo elements vs pseudo classes
- simple css reset
- Array filterUntil function implementation for javascript