ES6 Modules:
Put Down The Hacks And Nobody Gets Hurt

Alex Russell <slightlyoff@google.com>
LondonJS, August 20, 2012
@slightlylate

Some Modular Pre-History

Enter The Modern, Big Frameworks

goog.provide('goog.ui.tree.TreeControl');

goog.require('goog.events.EventType');
goog.require('goog.events.FocusHandler');
goog.require('goog.events.KeyHandler');
goog.require('goog.ui.tree.BaseNode');
goog.require('goog.ui.tree.TreeNode');
goog.require('goog.ui.tree.TypeAhead');

...Or

YUI.add('my-module', function (Y) {
   Y.MyModule = {
       sayHello: function () {
           console.log('Hello!');
       }
   };
}, '0.0.1', {
    requires: ['node', 'event']
});
YUI().use('my-module', 'othermodule', function (Y) {
    Y.MyModule.sayHello();
    Y.OtherModule.whatevs();
});

The only two syntax-free choices

  1. Synchronous require
    • Reads well
    • Needs a build system for deploy...
    • ...or fast, local I/O
  2. Async require
    • Code in callbacks -- but you IFFE'd anyway
    • Predictable perf
    • Build tools optional for longer

CommonJS/Node Style

math.js

exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
        sum += args[i++];
    }
    return sum;
};

increment.js

var add = require('math').add;
exports.increment = function(val) {
    return add(val, 1);
};

AMD Style

define("dijit/Tree",
  ["dojo",
   "dijit",
   "text!dijit/templates/TreeNode.html",
   "text!dijit/templates/Tree.html",
   "dijit/_Widget",
   "dijit/_Container",
   "dijit/_Contained"],
    function(dojo, dijit) {
      dojo.declare("dijit.Tree", ... );
      return dijit.Tree;
    });



...Now you have two problems.
Jamie Zawinski

ES.next Modules

DropDownButton.js

module Widgets {
  // Module-relative URLs
  module events from 'goog/events.js';
  // Destructuring & renaming
  import {EventType, FocusHandler, KH: KeyHandler} from events;
  // Splat imports
  import * from 'goog/widget.js';

  export let collection = [];
 
  export class DropDownButton extends Widget {
    constructor(attributes) {
      super(attributes);
      // ...
    }
  }
}

What You Really Need To Know

CAN HAZ MODULZ NAO?!

Require-HM

Traceur

Stop fighting, start sharing!

Thank you!

Questions?

@slightlylate