Working with ES6 Modules

ES6 introduced some amazing features that made our lives easier and more enjoyable. In this post we’re going to see how to work with ES6 modules.

There are a few ways to import and export ES6 modules, depending on what we want to achieve.

Single default export

We can export a module using export default.

const sum = (x, y) => {
    return x + y
}

export default sum // <= exports the constant sum as default

In this case, because we’re exporting the module as default we can assign any name later when we import the module in a different file:

import addition from './module'

addition(2, 3) // => 5

In this same way, we can export a module containing a collection of elements.

const sum = (x, y) => {
  return x + y
}

const text = 'this is the text'

export default {
  sum,
  text
}

And again, we can assign any name to that module when we import it and access its properties and methods:

import obj from './module'

console.log(obj.text)

Named Exports

The other way to export modules is by assigning a name:

export const sum = (x, y) => {
  return x + y
}

In this case, we need to specify the name of the module we’re importing in brackets:

import { sum } from './module'

Multiple Named Exports

We can export multiple modules in the same file and assign a name to each one of them:

export const sum = (x, y) => {
  return x + y
}

export const substract = (x, y) => {
  return x - y
}

And again we need to specify the modules that we’re importing:

import { sum, substract } from './module'

const result1 = sum(7, 5) // => 12
const result2 = substract(7, 5) // => 2