JavaScript Modules explained

js modules

commonjs

umd

module bundler

ES6 modules

amd

Browserify

Webpack

Rollup

What are modules?

  • small units of independent, reusable code
  • highly self-contained with distinct functionality, allowing them to be shuffled, removed, or added as necessary, without disrupting the system as a whole
  • Good authors divide their books into chapters and sections; good programmers divide their programs into modules

Benefits

  • Reusability
  • Maintainability
  • Dependency resolution
  • Encapsulation (namespacing)

Anonymous closure

(function(){
    // todo
}())
(function($){
    // jQuery plugin
}(jQuery))
  • creates own closure
  • can access global variables
  • can declare local variables without accidentally overwriting existing global variables

CommonJS

server oriented

  • Standard designed by volunteer working group
  • Node.js uses CommonJS modules
  • Synchronous
// testModule.js
function testModule() {
  this.hello = function() {
    return 'hello!';
  }

  this.goodbye = function() {
    return 'goodbye!';
  }
}

module.exports = testModule;
// consumer.js
const test = require('testModule');

const testModuleInstance = new test();
testModuleInstance.hello(); // 'hello!'
testModuleInstance.goodbye(); // 'goodbye!'

Asynchronous Module Definition (AMD)

browser oriented

// consumer.js
define(['myModule'], function(myModule) {
    myModule.hello();
    myModule.goodbye();
});

/* Alternative syntax */
define(function (require) {
    const myModule = require('myModule');

    myModule.hello();
    myModule.goodbye();
});
// myModule.js
define([], function() {
  return {
    hello: function() {
      return 'hello';
    },
    goodbye: function() {
      return 'goodbye';
    }
  };
});
  • In many cases it uses AMD as a base, with special-casing added to handle CommonJS compatibility

  • capable of working on both client and server

Universal Module Definition (UMD)

both client and server

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
      // AMD
    define([], factory);
  } else if (typeof exports === 'object') {
      // CommonJS
    module.exports = factory();
  } else {
    // Browser globals (Note: root is window)
    root.returnExports = factory();
  }
}(this, function () {
  // Methods
  function private(){};
  function hello(){}; 
  function goodbye(){};

  // Exposed public methods
  return {
      hello: hello,
      goodbye: goodbye
  }
}));

ES2015 Modules

  • compact and declarative syntax
  • asynchronous loading
  • better support for cyclical dependencies
  • imports are live read-only views of the exports
  • Downside: use use a transpiler for use in browser
// testModule.js
export default function testModule() {
  function hello() {
    return 'hello!';
  }

  function goodbye() {
    return 'goodbye!';
  }
}

// consumer.js
import testModule from 'testModule';
// or
import { hello } from 'testModule'; 
import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>Hello World!</div>
    );
  }
}

export default App;

Module bundling/loading

Simply put, it is the process of grouping modules (and their dependencies) into a single file (or group of files) in the correct order.

Webpack

  • New kid on the block
  • Super popular
  • Offers additional features such as code splitting and treeshaking
// testModule.js
export default function testModule() {
  function hello() {
    return 'hello!';
  }

  function goodbye() {
    return 'goodbye!';
  }
}

// consumer.js
import { hello } from 'testModule'; 
// testModule.js
export default function testModule() {
  function hello() {
    return 'hello!';
  }
}

Tree shaking

Which one wins?

¯\_(ツ)_/¯

  • There isn't a single winner
  • Competition breeds innovation
  • The web has always succeeded on having multiple ways of doing things

Resources

  1. JavaScript Modules: A Beginner's Guide, Preethi Kasireddy
    https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc#.t5pfp5lmf
  2. Brief history of JavaScript Modules, SungTheCoder
    https://medium.com/@sungyeol.choi/javascript-module-module-loader-module-bundler-es6-module-confused-yet-6343510e7bde#.1ddueq67z
  3. Understanding JavaScript Modules
    https://spring.io/understanding/javascript-modules
  4.  

JavaScript Modules explained

By Carlos Filoteo

JavaScript Modules explained

  • 596