bradxr
8/8/2018 - 4:13 PM

ES6 Modules

Module - piece of reusable code that can easily be incorporated into other JavaScript files Stored in separate files, one file per module Two options when creating and exporting a module: you can export multiple JavaScript objects from a single module, or one JavaScript object per module Can be used on any JavaScript type i.e. primitives, objects, arrays, and functions

Src - “Learning React by Alex Banks and Eve Porcello (O’Reilly). Copyright 2017 Alex Banks, Eve Porcello, 978-1-491-95462-1.”

// the module and two functions are exported
export const print(message) => log(message, new Date())

export const log(message, timestamp) =>
  console.log(`${timestamp.toString()}: ${message}`)


// one variable is exported from a module
const freel = new Expedition("Mt. Freel", 2, ["water", "snack"])

export default freel


// modules can be used in other JavaScript files using the import statement
// modules with multiple exports can utilise object destructuring
// modules that use export default are imported into a single variable
import {print, log} from './text-helpers'
import freel from './mt-freel'

// modules can be scoped locally under different variable names
import { print as p, log as l} from './text-helpers'

// can also import everything as a single variable
import * as fns from './text-helpers'