This article will show you how to get started with ES6 modules in node with Babel.

If you need to setup your environment, check out this article.

Exports

In your library, export functions and classes this way:

// ----------
// module1.js
// ----------

export const life = "42";

export function add(x, y) {
return x + y;
}

export function multiply(x, y) {
return x * y;
}

export class Car {

constructor(color) {
this.color = color;
}

getCarColor() {
return this.color;
}
}

Imports

Import specific

You can specify which value you wish to import using the following syntax:

import {life, add as addition} from './module1'

console.log(life); // 42
console.log(addition(1,1)); // 2

Note how you can use as to change the name of some of the values.

Import all

import module1 from './module1'

var car = new module1.Car("blue");

console.log(car.getCarColor()); // blue

Default export

If your module only has one value to export, use default when exporting that value.


// Export - myModule.js
export default function () {}

// Import
import myFunc from './myModule';
myFunc();

This information should be enough for you to get started with ES6/ES2015 modules. If you need to know more, I would recommend this article.