ES Modules (import and export)

Modules provide a way to separate our code across multiple files. This makes our applications much easier to maintain and easier for multiple developers to work on at the same time. This new language feature does the same thing module.exports and require perform in the Node.js environment, but replaces it with the syntax export and import respectively.

For more information, see ES6 In Depth: Modules.

default export

The main export of a file is known as the default export. There can only be one default export from a file (though there may be more non-default exports). To export a value, object, array, function, or pretty much anything from a module, just preface it with export default.

// utility.js
export default function importantFunc (s1, s2) {
return s1 + ' ' + s2
}

This makes it available to import:

// app.js
import importantFunc from 'utility.js'
const combined = importantFunc('pretty', 'cool')

As we import it, we may choose another name for it:

// app.js
import join from 'utility.js'
const combined = join('pretty', 'cool')

export (not default)

In a file we may also have many things we wish to export. In this case we preface them with the word export, as follows:

// utility.js
export function joinStrings (s1, s2) {
return s1 + ' ' + s2
}
export function capitalise (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}

As there are now multiple exports, we must use their stated name to access them. To import and use values like the joinStrings function above, we might do it in two ways:

// app.js
import * as utils from 'utility.js'
const combined = utils.joinStrings('pretty', 'cool')

or

// app.js
import { joinStrings } from 'utility.js'
const combined = joinStrings('pretty', 'cool')