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:

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.

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 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

Usage

  • ES2015 module import
import * as myModule from 'myModule';
  • CommonJS module require
var myModule = require('myModule');
  • ES2015 and CommonJS module use
myModule.myFunction('Arg1');
  • AMD module require
require(['myModule'], function ( myModule ) {
  // ...
  // AMD module use
  myModule.myFunction('Arg1');
  // ...
});

Resolver

A resolver search a module in the file system.

Plugin:

Env:

  • NODE_PATH env

See also Javascript - Module Loader (Script Loader)

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();

Documentation / Reference


Powered by ComboStrap