Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created June 5, 2014 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhei/8efaa3ad577e125a5d3d to your computer and use it in GitHub Desktop.
Save shuhei/8efaa3ad577e125a5d3d to your computer and use it in GitHub Desktop.

JS Modules

  • RequireJS
  • CommonJS
  • ES6 Modules

Why modules?

  • Divide et impera
  • Avoid global variables

Namespace pattern

(function() {
  window.M3 = window.M3 || {};
  M3.Views = window.M3.Views || {};

  function AwesomeView() {}

  AwesomeView.prototype.doSomething = function() {
  };

  M3.Views.AwesomeView = AwesomeView;
})();

// Somewhere else...
var awesome = new M3.Views.AwesomeView();
awesome.doSomething();

ES6 Modules

ES6: EcmaScript 6. JavaScript and JScript are implementations of EcmaScript. ActionScript...

Future standard.

Compatibility?

export var hello = 12;
export var world = 23;
import { hello, world } from 'module';

console.log(hello + world);

es6-tools by Addy Osmani

RequireJS

AMD: Asyncronous Module Definition

Module definition. Asynchronous script loading.

However, scripts are usually bundled in production environment. Bundle with r.js.

define(['dep1', 'dep2'], function(dep1, dep2) {
  // Do something with dep1 and dep2...

  return {
    foo: 123,
    bar: 234
  };
});

CommonJS

Origin?

Works well on Node.js.

var http = require('http');
var url = require('url');

//

Browserify allows us to write CommonJS modules for browsers. Also, package management with npm.

Doesn't work well with non-CommonJS scripts...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment