JavaScript Modules
Module
A group of code and data related to particular piece of functionality. It encapsulates implementation details, exposes a public API and is combined with other modules to build a larger application.
Goals of modularity
- Create a higher level of modularity.
- Encapsulation
- Reusability
- Simplfy dependency management
Module Patterns in ES5
⚽ Immediately invoke function expression (IIFE)
It provides the encapsulation and no of the variable we store in a global scope.
- It is an anonymous function that invoked at a time of declaration.
- It reduces the global scope and global scope pollution.
- It provides encapsulation.
- No dependency management
Ex:
(function(){
})();
⚽ revealing Module Pattern
- Implementing a module as a Singleton
var scoreBoard = function(){
function printMessage(){
var message = "World";
console.log("Hello" + world);
}
return{
showMessage = printMessage;
}
}();
If we create a function like above it will be available in global scope i.e., available in window object. IIFE brackets are important i.e., highlighted in bold above.
- Implementing a module as a constructor function
var scoreBoard = function(){
function printMessage(){
var message = "World";
console.log("Hello" + world);
}
return{
showMessage = printMessage;
}
};
var myScoreBoard = new scoreBoard();
myScoreBoard.showMessage(); (These steps are important for constructor function and here there is no IIFE brackets)
Module Formats
👉 It is actually define the syntax.
- Asynchronous Module Definition(AMD) - (Non-native format)
- CommonJS -(Non-native format)
- ES2015 (Native format - No need helper libraries or packages in order to write them. If u write it in typescript then transpilation required)
Module Loaders
👉 It is the Execution.
- requireJS (supports AMD)
- systemJS (supports AMD,CommonJS,UMD and System.register)
The relation between Module formats and Module Loaders:- It is the same as the relation between javascript and the browser.
Module Bundlers
Examples: Browserify, webpack etc., It is really an alternative to Module Loader
Browserify bundles only commonjs modules and only one file will be created i.e., bundle.js
Webpack is the latest bundler and it bundles cmmonjs,amd and es2015 modules., It also do the code splliting and will create multiple bundle files. That means it is not only bundles javascript but also bunldes CSS, images and other static assets....etc.