Javascript - Module


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:

To learn how to create a module, the best is to follow the tutorial of a Module bundler



One or several modules are distributed via the package 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.

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() {
  } = function() {

Module Pattern

See the design pattern with closure: Javascript - Module Pattern


See Loader


A resolver search a module in the file system.



  • NODE_PATH env

See also Javascript - Module Loader (Script Loader)


Generally, exporting from a module involves adding properties to a value like:

  • exports
  • or module.exports


function foo() {
    // ...
module.exports = foo;


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.

Documentation / Reference

Task Runner