JavaScript: Modules

Module files contain JavaScript to be reused in a different setting.

Importing – Using Modules

import myModule from ‘./modules/theModule.mjs’
// the name myModule is your choice and applies to the “default feature” in the module file

import {theFunc1, theFunc2} from ‘./modules/theModule.mjs’
// theFunc1/2 are the names for the functions in the module file

import {theFunc1 as myFunc1, theFunc2 as myFunc2} from ‘./modules/theModule.mjs’
// referred to as myFunc1 within the local code

import myModule, {theFunc1 as myFunc1} from ‘./modules/theModule.mjs’
// both the default feature and specific function

import * as theModule from ‘./modules/theModule.mjs’
// all items in module can be obtained using theModule.theFunc1() etc.

Exporting – Defining Modules

To define a function/class/variable as available through modules, just prefix with ‘export’

export function myFunction(){….

Can also define as normal and then add export at the end of the file:

function myFunction(){… }

export {myFunction, myClass, myVar}

can also specify external names

export {myFunction as theFunction, myClass as theClass, myVar}

You can specify at most one item using the default keyword:

export default myFunction
export {myFunction as default}
export default {myFunction, myClass, myVar}

If your code uses code from another module you can re-export the code from that module:

export {otherFunction, otherClass, otherVar} from ‘./modules/myModule’