Javascript - Module

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

1 - About

Code Shipping - (Package|Module|Library) functionality in Javascript.

A package (library) functionality in javascript is created from one or several module.

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

This section introduce you to the serveral ways that exist in JavaScript in order to implement a module mechanism.

Until the ES6 module definition, most of the module were defined by the module (script) loader

3.1.1 - With import and export statement

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

3.1.2 - Pattern of Javascript

Module can also be created with the JavaScript structure primitive:

  • A global variable
  • or the module pattern
Advertising - Global Variables
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() {
 }(globalVariable));; - Module Pattern

See the design pattern with closure: Javascript - Module Pattern

3.2 - Usage

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

3.3 - Resolver

A resolver search a module in the file system.



  • NODE_PATH env

4 - Documentation / Reference

web/javascript/module.txt · Last modified: 2019/05/25 15:27 by gerardnico