JavaScript es6 modules import, export

Java scrips modules are libraries that export importable properties.

With modules you can create reusable independent separate components es6 modules should provide one or more exports.

exports can be ie a function or an object take for instance you created a math library you can use the syntax below to create a module.

// saved as lib-math.js
export function cube(num) {
    return num * num * num

To make use of lib-math above in a simple calculator function you can import it as

// saved as calculator.js
Import {cube} from "./lib-math"
function calculator(num) {
    return cube(num)

// calculator(5) // returns 125
// calculator(3) // returns 27
// calculator(2) // returns 8

Alternative ways to export
You can export a function as in the example above or you can export functions as an object assuming you have more than one

export {cube, sqrt, .....}

Ways to import a module importing modes is done by the follow keyword following by from proceeded by the relative path or module name for modules ie

Import method from "./packages.js"

Importing more than one method is done using a syntax looking like

Import {method, method2, .....}

You can also rewrite a module import name

Import {method as something}


Popular posts from this blog

How to set content disposition header for nginx server to force content download

Animated daylight on HTML5 Canvas

How to make a static http server in nodejs using express

JS13K Preparation

Adding Gameover and introduction screen on HTML Canvas