JS Modules

What are they?

  • modules to programs are like chapters to a book
  • they separate the code into distinct sections that interact with each other in an organized way
  • increase the program readability and robustness

Maintainability

  • Well designed modules aim to lessen dependencies on other code
  • updating a single module is easier when it's decoupled

Benifits

Scoping

  • Each module has it's own scope
  • Ability to separate private/internal details from the public interface with outside code

Benifits

Reusability

  • Between different projects
  • Write and test once and use everywhere 

Benifits

Javascript provides a few module systems

  • ES5 module pattern
  • ES6 modules
  • CommonJS (node)
  • AMD
  • a few more ...

ES5 modules

(function () {
  // We keep these variables private inside this closure scope
  
  var myGrades = [93, 95, 88, 0, 55, 91];
  
  var average = function() {
    var total = myGrades.reduce(function(accumulator, item) {
      return accumulator + item}, 0);
    
      return 'Your average grade is ' + total / myGrades.length + '.';
  }

  var failing = function(){
    var failingGrades = myGrades.filter(function(item) {
      return item < 70;});
      
    return 'You failed ' + failingGrades.length + ' times.';
  }

  console.log(failing());

}());

// ‘You failed 2 times.’

CommonJS (Node)

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

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

module.exports = myModule;
var myModule = require('myModule');

var myModuleInstance = new myModule();
myModuleInstance.hello(); // 'hello!'
myModuleInstance.goodbye(); // 'goodbye!'

myModule.js

app.js

Exercise

ES6 modules

export let counter = 1;

export function increment() {
  counter++;
}

export function decrement() {
  counter--;
}
import * as counter from 'counter';

console.log(counter.counter); // 1
counter.increment();
console.log(counter.counter); // 2

counter.js

app.js

Module bundling

Browsers need one bundle (file) of ES5 code because of:

  • compatibility
  • performance reasons

Module bundlers

  • Webpack
  • Browserify

Webpack

npm install webpack -g
webpack entrypoint.js app.bundle.js

JS Modules

By Gabi Mor

JS Modules

  • 567