What is ES6?

ES6 or ES2015 is the new standard to write JavaScript. It provides some really cool new features to make writing Javascript much easier and more scalable. At the time of this article, many parts of ES6 are not yet supported in many places including imports and exports. However, with a transpiler like Babel, we can use them right away. For this tutorial, I use babel.

So how do imports and exports work with ES6?

Right now, you are probably used to the require() syntax. A module returns what is exported. With ES6, we can simply this.

Take a look at the following code:

//module.js
export default class {
  constructor() {
    console.log("GOOD");
  }
}

export class Foo {
  constructor() {
    console.log("FOO");
  }
}

export const url = "http://www.kaplankomputing.com";

export function bar() {
  console.log("bar");
}

Here, we export two classes, one constant, and one function. Of note, you will notice our first export is named default. With ES6 each module can have ONE default export. It can not have more than one default. It is not recommended to mix default exports with “named” exports. However, for the purpose of this tutorial, I do mix them.

Now that we exported, how do we import?

Lets take a look at the following code in our index.js file.

import Custom, {Foo, url, bar} from './module';
const custom = new Custom();
const foo = new Foo();
bar();
console.log(url);

For our import statement, you will notice we import all 4 exports. 3 of these are inside brackets, with one outside of brackets. The one outside of brackets is our default export. Default exports always go outside of brackets. You can name your default export whatever you like. In this case, I named it Custom. Our next three import names all match up exactly with the export names in module.js Also, because our module.js file is not in node_modules/, we specify the location of the file.

Our next three lines, we instantiate our classes, call our function, and log our constant.

Running index.js produces the following input:

GOOD
FOO
bar
http://www.kaplankomputing.com

We have successfully mastered imports and exports with ES6!

To see the code in action, view the repo here.