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

Advertising

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
3.1.2.1 - Global Variables
GlobalVariablesModule.js
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.1.2.2 - 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
myModule.myFunction('Arg1');
  • AMD module require
require(['myModule'], function ( myModule ) {
  // ...
  // AMD module use
  myModule.myFunction('Arg1');
  // ...
});
Advertising

3.3 - Resolver

A resolver search a module in the file system.

Plugin:

Env:

  • NODE_PATH env

4 - Documentation / Reference

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