Javascript - Module
About
Code Shipping - (Module|Component) functionality in Javascript.
A module is different from a script file because:
- it defines a well-scoped object that does not pollute the global namespace.
- It list explicitly its dependencies
Javascript doesn't have one definition to create a module functionality but several. See format.
The most important is:
- For Node.js, you will use the CommonJS format. See Node - Module (ie NPM Module)
- For both browsers and Node.js, you will use the UMD format
To learn how to create a module, the best is to follow the tutorial of a Module bundler
Management
Distribution
One or several modules are distributed via the package format.
Format
This section introduce you to the serveral ways that exist in JavaScript in order to implement a module mechanism.
Most libraries are written as an UMD libraries
Until the ES6 module definition, most of the module were defined by the module (script) loader
With import and export statement
The following format define a import/export mechanism in order to link code between modules.
- Universal Module Definition (UMD) attempt to bridge the differences between AMD and node.js
- Asynchronous Module Definition (AMD) and its define and require statement
- CommonJS and its require() statement and exports object
- Node.js modules (an extension to CommonJS Modules/1.1) - server-side environments
- ES2015 module and its import and export statement
Pattern of Javascript
Module can also be created with the JavaScript structure primitive:
- A global variable
- or the module pattern
Global Variables
Also known as the How to create a javascript global library (namespace pattern)
var MyModule = function() {};
where the dependency are in the global scope
Same as below (Jquery uses this pattern) with an Immediately invoked function expression (IIFE)
var globalVariable = {};
(function (globalVariable) {
// Private inside this closure scope
var privateFunction = function() {
console.log('privateFunction');
}
globalVariable.foo = function() {
console.log('publicFunction');
};
}(globalVariable));
globalVariable.foo();
Module Pattern
See the design pattern with closure: Javascript - Module Pattern
Loader
See Loader
Resolver
A resolver search a module in the file system.
Plugin:
Env:
- NODE_PATH env
Export
Generally, exporting from a module involves adding properties to a value like:
- exports
- or module.exports
Example:
function foo() {
// ...
}
module.exports = foo;
Import
When the path to the module is not relative, the resolver looks into the node_modules folder.
Example: commonjs
var express = require("express");
var app = express();
How to define, get or set the type of module in a package?
The type property in package.json file defines the type of module that the package/workspace contains.