ES6 - Modules


// ES6 - Modules:

We have 2 files, app.js and foo.js


var foo = 2;
var bar = 3;
export {foo, bar};


import (foo) from 'app';
console.log(foo); // 2

In app.js, we have two variables, foo and bar.  In the bottom, we used the 
export keyword to export foo and bar.  These are what we call a named export.  
We can also do:

export var foo = 2;
export var bar = 3;

And in the other file, we can import these variables:

import {foo} from 'app';

Along with named exports, modules can also have what is called a default export:

export default function() {
  return 2;

and we can import it using:

import foo from 'app';
console.log(foo()); // 2

Notice that for default export, we do not use the curly brace when we import it.

We can have a mixture of both default export and named exports.  Imagine utility 
libraries such as underscore or low dash.  They may have a default export, which 
is the entire underscore object, but they might also have named exports for 
every single functions they provide.

We can import all the named exports in one go:

module stuff from 'app'; // 2 // 3

Loading ES6 module is a little trickier.

In ES6-compliant browser, we would use the System keyword to load modules 
asynchronously.  To make our code work with the browsers of today, we will use 
the SystemJS library as a polyfill:

<script src="/node_module/systemjs/dist/system.js"></script>
  var promise = System.import('app')
    .then(function() {
    .then(null, function(error) {
      console.error('Failed to load');
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License