Saturday, October 21, 2017

JavaScript ES2015 ES6 Module Support

ES6 lets you natively define and use modules.

Since most Web Browsers do not currently support this feature, the code must be transpiled into ES5 using a tool such as Babel. This must occur at build time as a development step.

The code is transpiled into AMD or CommonJS module format by the tool. The HTML source then references RequireJS/SystemJS that is used by the Browser to load the modules in the depedency order at runtime.

To avoid use of a runtime module loader (for efficiency sake), the code can be bundled using bundlers such as Webpack (AMD module format) or Browserify (commonjs module format; commonly used to package nodejs code for use in a Browser) as a development step. The development step takes the transpiled source code and creates one or more bundled js files that contains code in the module dependency order (hence eliminating the need for a runtime module loader).

Module Export Syntax

Export functions inline

// somefile.js
export function doSomething(doWhat){
}

export function printResults(){
}

// do not export a private function
function privateHelper(){
}

// export a variable
export var pi = 3.142

Export public functions with a declaration

// somefile.js
function doSomething(doWhat){
}

function printResults(){
}

function privateHelper(){
}

// export a variable
var pi = 3.142

// we are renaming printResults to print when exporting
// we are also exporting a variable (can do the same for classes)
// privateHelper is not a part of the Api
export { doSomething, printResults as print, pi}

Specify Default Export

// somefile.js
export function doSomething(doWhat){
}

// make printResults the default function exported out of this module
export default function printResults(){
}

function privateHelper(){
}

// export a variable
export var pi = 3.142

Module Import Syntax

// import all public functions from the module
// methods can be invoked on extModule, e.g. extModule.printResults()
import * as extModule from './somefile.js'

// selective import of functions
// functions are invoked as usual e.g. printResults()
import {doSomething, printResults} as extModule from './somefile.js'

// selective import of functions with an alias
// function are invoked with its alias e.g. print()
import {doSomething, printResults as print} as extModule from './somefile.js'

// import the default function as print()
import print from './somefile.js'

// import the default function and another function
// print() is exported as default, also import doSomething function
import print, {doSomething} from './somefile.js'