Javascript - Module

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

3 - Management

3.1 - Distribution

One or several modules are distributed via the package format.

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

3.2.1 - With import and export statement

The following format define a import/export mechanism in order to link code between modules.

3.2.2 - Pattern of Javascript

Module can also be created with the JavaScript structure primitive:

  • A global variable
  • or the module pattern
3.2.2.1 - 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();


3.2.2.2 - Module Pattern

See the design pattern with closure: Javascript - Module Pattern

3.3 - 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');
  // ...
});

3.4 - Resolver

A resolver search a module in the file system.

Plugin:

Env:

  • NODE_PATH env

See also Javascript - Module Loader (Script Loader)

3.5 - Export

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

  • exports
  • or module.exports

Example:


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

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

4 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap