JavaScript Module pattern provides a way to wrap public, private methods (and variable) into a single entity. The functions or variables defined in a module are not visible outside unless we explicitly export them.
Module basics
ES6 modules are stored in files.There’s no special module keyword.
ES6 modules are automatically strict-mode code, even if we don’t write "use strict"
. We can use import
and export
in modules.
Basic usage
Here very basic example for module export and import. Here we are going to create two utility functions.
generateRandom()
: Generates a random number.
sum()
: Adds two numbers.
// utils.js
function getRandomNumber() {
return Math.random();
}
function getSum(a, b) {
return a + b;
}
export { getRandomNumber, getSum }
We can also rename the values while exporting like this:
// utils.js
// Rest of the declaration...
export { getRandomNumber as random, getSum as doSum }
Using above utils modules in our main javascript file
// main.js
import { getRandomNumber, getSum } from './utils';
console.log(getRandomNumber()); // some random number
console.log(getSum(2, 5)); // 7