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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ----------
// 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:

1
2
3
4
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

1
2
3
4
5
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.

1
2
3
4
5
6
7
// 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.