What is Module in javascript ES6 ?

Module in javascript is a piece of reusable code that can easily be use into
other JavaScript files

JavaScript modules are stored in separate files, one file per module. There are two
options when creating and exporting a module: you can export multiple JavaScript
objects from a single module, or one JavaScript object per module

Example of ES6 module

/text-helpers.js

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

export default can be used in place of export when you wish to export only one
type. Again, both export and export default can be used on any JavaScript type:
primitives, objects, arrays, and functions

Example

./mt-freel.js

const freel = new Expedition("Mt. Freel", 2, ["water", "snack"])
export default freel

Modules can be consumed in other JavaScript files using the import statement. Modules with multiple exports can take advantage of object destructuring. Modules that use export default are imported into a single variable

Example

import { print, log } from './text-helpers'
import freel from './mt-freel'
print('printing a message')
log('logging a message')
freel.print()

we can scope module variables locally under different variable names

import { print as p, log as l } from './text-helpers'
p('printing a message')
l('logging a message')

Table of Contents

CommonJS

CommonJS is the module pattern that is supported by all versions of Node.js. we can still use these modules with Babel and webpack. With CommonJS, JavaScript
objects are exported using module.exports

Example:

./txt-helpers.js

const print(message) => log(message, new Date())
const log(message, timestamp) =>
 console.log(`${timestamp.toString()}: ${message}`}
module.exports = {print, log}

CommonJS does not support an import statement. Instead, modules are imported with the require function

Example:

const { log, print } = require('./txt-helpers')

Leave a Comment