Introduction

ES6 Modules are the defacto way to handle code reusability in the form of modules. JavaScript came from its humble beginnings with the script tag being the only way to use modules. Attempts were made (details beyond the scope of this post) to have a module system in place leading to the rise of the likes of UMD and AMD systems.

More about UMD & AMD in this blog post

ES2015 introduced ESM (ES6 Modules) which allows:

  • Default export/imports
  • named exports/imports
  • wild card imports(for named imports)

Default export(s)/default import(s)

Take for example theme.js:

export default THEME = 'LIGHT_THEME'

You can have only one default export per file.

Import from the default export:

Inside index.js:

// we import THEME as
import THEME from './theme'

Named exports

With named exports, we export each export individually or all at the bottom of the actions.js file:

// export individually
export const LOAD_ITEMS = 'LOAD_ITEMS'
export const SAVE_CART = 'SAVE_CART_ITEMS'
export const DELETE_ITEMS = 'DELETE_ITEMS'

or all at the bottom of the file, actions.js:

const LOAD_ITEMS = 'LOAD_ITEMS'
const SAVE_CART = 'SAVE_CART_ITEMS'
const DELETE_ITEMS = 'DELETE_ITEMS'
export { LOAD_ITEMS, SAVE_CART, DELET_ITEMS }

importing for named inside index.js:

// we import each by its name
import {LOAD_ITEMS, SAVE_CART, DELETE_ITEMS} from './actions'

Bonus, with wild card import:

// imports all exports from actions under one collective name 'action'
import * as actions from './actions'
// accessing a single item
const deleteAction = actions.DELETE_ITEMS

The example assumes that files index.js and actions.js are on the same level(path) in the file system.


Follow me on Twitter @nkmurgor where I tweet about interesting topics.