SlideShare a Scribd company logo
1 of 51
The Many Ways to Build
Modular JavaScript
Tim Perry
Tech Lead & Open-Source Champion at Softwire
@pimterry / github.com/pimterry / tim-perry.co.uk
JavaScript
 Originally designed by Brendan Eich for Netscape in mid-1995 as
LiveScript, based on his ideas from Scheme and Self, and implemented
over 10 days ‘or something worse than JS would have happened’.
 LiveScript ships in Netscape 2.0 that September
 Renamed to JavaScript three months later to confuse as many people as
possible for marketing purposes
 Standardisation begins a year later (now as ECMAScript), after everybody
has already implemented their own unique take.
 First ECMAScript spec is published in June 1997.
 16 years later, it’s the de facto standard language for all code on the
largest common platform in the world (and everybody still calls it
JavaScript)
JavaScript
Some great bits:
 Dynamic typing
 First-order functions & closures
Some features that just need removing:
 The ‘with’ keyword
 Much of type coercion
 Automatic semicolon insertion
Some fundamental structures that are hugely counter-intuitive:
 How ‘this’ and variable scope work
 Prototypes
Some clearly relevant features that don’t exist:
 Simple class definitions
 Tail-call optimizations
 A mechanism to allow structured modular code
Why?
coffeeFunctions.js:
function askAboutSugar() { … }
function askAboutMilk() { … }
function prepareMug(sugar, milk) { … }
function requestuserEmptyGrounds() { … }
function requestuserEmptyTray() { … }
function grindBeans() { … }
function putGroundsInFilter() { … }
function heatWater() { … }
function waterHotEnough() { … }
function pourCoffeeInMug () { … }
function serveMugToUser() { … }
index.html:
<html><body>
<button onclick=‚makeCoffee()‛>Make Coffee</button>
<script src=‚coffeeFunctions.js‛></script>
<script>
function makeCoffee() {
var sugars = askAboutSugar();
var milk = askAboutMilk();
prepareMug(sugars, milk);
while (!groundsAreEmpty) requestUserEmptyGrounds();
while (!dripTrayIsEmpty) requestUserEmptyTray();
grindBeans();
putGroundsInFilter();
heatWater();
while (!waterHotEnough()) wait();
pourCoffeeInMug();
serveMugToUser();
};
</script>
</body></html>
Why?
JavaScript uses lexically-defined function scoping
Variables definitions are either in local scope or global scope
function f() {
var localVar = ‚a string‛;
}
function f(localParameter) {
localParameter = ‚a string‛;
}
function f() {
function localFunction() {
}
}
var globalVar = ‚a string‛;
function g() {
globalVar = ‚a string‛;
}
function g() {
window.globalVar = ‚a string‛;
}
window.window.window.window === window;
Why?
index.html:
<html><body>
<button onclick=‚makeCoffee()‛>Make Coffee</button>
<script src=‚coffeeFunctions.js‛></script>
<script>
function makeCoffee() {
var sugars = askAboutSugar();
var milk = askAboutMilk();
prepareMug(sugars, milk);
while (!groundsAreEmpty) requestUserEmptyGrounds();
while (!dripTrayIsEmpty) requestUserEmptyTray();
grindBeans();
putGroundsInFilter();
heatWater();
while (!waterHotEnough()) wait();
pourCoffeeInMug();
serveMugToUser();
};
</script>
</body></html>
coffeeFunctions.js:
function askAboutSugar() { … }
function askAboutMilk() { … }
function prepareMug(sugar, milk) { … }
function requestuserEmptyGrounds() { … }
function requestuserEmptyTray() { … }
function grindBeans() { … }
function putGroundsInFilter() { … }
function heatWater() { … }
function waterHotEnough() { … }
function pourCoffeeInMug() { … }
function serveMugToUser() { … }
Why?
index.html:
<html><body>
<button onclick=‚makeCoffee()‛>Make Coffee</button>
<script src=‚coffeeFunctions.js‛></script>
<script>
function makeCoffee() {
var sugars = askAboutSugar();
var milk = askAboutMilk();
prepareMug(sugars, milk);
while (!groundsAreEmpty) requestUserEmptyGrounds();
while (!dripTrayIsEmpty) requestUserEmptyTray();
grindBeans();
putGroundsInFilter();
heatWater();
while (!waterHotEnough()) wait();
pourCoffeeInMug();
serveMugToUser();
};
</script>
</body></html>
coffeeFunctions.js:
function askAboutSugar() { … }
function askAboutMilk() { … }
function prepareMug(sugar, milk) { … }
function requestuserEmptyGrounds() { … }
function requestuserEmptyTray() { … }
function grindBeans() { … }
function putGroundsInFilter() { … }
function heatWater() { … }
function waterHotEnough() { … }
function pourCoffeeInMug() {
stopHeatingWater();
openCoffeeTap();
pourWaterThroughFilter();
}
function serveMugToUser() { … }
Why?
Global state makes systems
hard to reason about
Why?
Encapsulation breaks systems
into component parts, which
can be clearly reasoned about
index.html:
<html>
<body>
<button>Make Coffee</button>
<script src=‚beanGrinder.js‛></script>
<script src=‚hotWaterSource.js‛></script>
<script src=‚coffeeMachineUi.js‛></script>
<script src=‚coffeeController.js‛></script>
<script src=‚coffeeMachine.js‛></script>
<script>
coffeeMachine = new CoffeeMachine();
coffeeMachine.ui.show();
</script>
</body>
</html>
Why?
coffeeMachine.js:
function CoffeeMachine() {
var grinder = new BeanGrinder();
var hotWater = new HotWaterSource();
var ui = new CoffeeMachineUi();
var cc = new CoffeeController(grinder, hotWater, ui);
}
beanGrinder.js:
function BeanGrinder() { … }
coffeeController.js:
function CoffeeController(grinder, hotWater, ui) { … }
hotWaterSource.js:
function HotWaterSource() { … }
Why?
Build reusable chunks of code
Why?
beanGrinder.js:
function BeanGrinder() {
var beans = ko.observable(new BeanSupply());
var grindStrategy = new GrindStrategy();
this.grindBeans = function () { … };
}
coffeeMachineUi.js:
function CoffeeMachineUi() {
this.onMakeCoffee = function (makeCoffeeCallback) {
$(‚button‛).click(makeCoffeeCallback);
$(‚beanTypes‛).draggable();
};
this.askForSugar = function () { … };
this.askForMilk = function () { … };
this.confirmCancelMyCoffeePlease = function () { … };
}
hotWaterSource.js:
function HotWaterSource() {
var dynamicsCalculator = new FluidCalc();
this.openTap = function () { … }
this.startHeating = function () { … }
this.stopHeating = function () { … }
}
Why?
beanGrinder.js:
function BeanGrinder() {
var beans = ko.observable(new BeanSupply());
var grindStrategy = new GrindStrategy();
this.grindBeans = function () { … };
}
coffeeMachineUi.js:
function CoffeeMachineUi() {
this.onMakeCoffee = function (makeCoffeeCallback) {
$(‚button‛).click(makeCoffeeCallback);
$(‚beanTypes‛).draggable();
};
this.askForSugar = function () { … };
this.askForMilk = function () { … };
this.confirmCancelMyCoffeePlease = function () { … };
}
hotWaterSource.js:
function HotWaterSource() {
var dynamicsCalculator = new FluidCalc();
this.openTap = function () { … }
this.startHeating = function () { … }
this.stopHeating = function () { … }
}
index.html:
<html><body>
<script src=‚jquery.js‛></script>
<script src=‚jquery-ui.js‛></script>
<script src=‚knockout.js‛></script>
<script src=‚beanSupply.js‛></script>
<script src=‚grindStrategy.js‛></script>
<script src=‚fluidDynamicsLib.js‛></script>
<script src=‚beanGrinder.js‛></script>
<script src=‚coffeeMachineUi.js‛></script>
<script src=‚coffeeController.js‛></script>
<script src=‚hotWaterSource.js‛></script>
<script src=‚coffeeMachine.js‛></script>
<script>
coffeeMachine = new CoffeeMachine();
coffeeMachine.ui.show();
</script>
</body></html>
Why?
Why?
Be explicit about your
component’s external
dependencies
Why?
1. Encapsulated state
2. Reusable code
3. Explicit dependency management
Immediately-Invoked
Function Expression (IIFE)
window.coffeeMachine.moduleName = (function ($, grindStrategy) {
[… some code using these dependencies…]
return aModuleObject;
})(window.jQuery, window.coffeeMachine.grindStrategy);
Immediately-Invoked
Function Expression (IIFE)
window.coffeeMachine.moduleName = (function ($, grindStrategy) {
[… some code using these dependencies…]
return aModuleObject;
})(window.jQuery, window.coffeeMachine.grindStrategy);
Immediately-Invoked
Function Expression (IIFE)
window.coffeeMachine.moduleName = (function ($, grindStrategy) {
[… some code using these dependencies…]
return aModuleObject;
})(window.jQuery, window.coffeeMachine.grindStrategy);
Immediately-Invoked
Function Expression (IIFE)
window.coffeeMachine.moduleName = (function ($, grindStrategy) {
[… some code using these dependencies…]
return aModuleObject;
})(window.jQuery, window.coffeeMachine.grindStrategy);
Immediately-Invoked
Function Expression (IIFE)
window.coffeeMachine.moduleName = (function ($, grindStrategy) {
[… some code using these dependencies…]
return aModuleObject;
})(window.jQuery, window.coffeeMachine.grindStrategy);
IIFE Module Benefits
 Code internals are encapsulated
 Dependencies are explicitly named
 Code is reusable (in contexts where the dependencies are already
available)
IIFE Module Problems
 Global state has to be used to store each module exported from
an IIFE module
 Namespacing requires manual initialization and management
 Module loading and ordering still have to be managed manually
Asynchronous Module
Definitions (AMD)
define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛],
function ($, ko, coffeeGrinder) {
[… make coffee or build some private state or something …]
return {
‚doSomethingCoffeeRelated‛ : coffeeMakingFunction,
‚usefulNumber‛ : 4,
};
}
);
Asynchronous Module
Definitions (AMD)
define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛],
function ($, ko, coffeeGrinder) {
[… make coffee or build some private state or something …]
return {
‚doSomethingCoffeeRelated‛ : coffeeMakingFunction,
‚usefulNumber‛ : 4,
};
}
);
Asynchronous Module
Definitions (AMD)
define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛],
function ($, ko, coffeeGrinder) {
[… make coffee or build some private state or something …]
return {
‚doSomethingCoffeeRelated‛ : coffeeMakingFunction,
‚usefulNumber‛ : 4,
};
}
);
Asynchronous Module
Definitions (AMD)
define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛],
function ($, ko, coffeeGrinder) {
[… make coffee or build some private state or something …]
return {
‚doSomethingCoffeeRelated‛ : coffeeMakingFunction,
‚usefulNumber‛ : 4,
};
}
);
Asynchronous Module
Definitions (AMD)
define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛],
function ($, ko, coffeeGrinder) {
[… make coffee or build some private state or something …]
return {
‚doSomethingCoffeeRelated‛ : coffeeMakingFunction,
‚usefulNumber‛ : 4,
};
}
);
Asynchronous Module
Definitions (AMD)
require([‚font!fonts/myFavFont‛, ‚less!styles/homeStyle‛, ‚domReady!‛],
function () {
showPageNowThatAllPrerequisitesAreLoaded();
}
);
Asynchronous Module
Definitions (AMD)
require([‚font!fonts/myFavFont‛, ‚less!styles/homeStyle‛, ‚domReady!‛],
function () {
showPageNowThatAllPrerequisitesAreLoaded();
}
);
index.html:
<html>
<script src=‚require.js‛
data-main=‚scripts/main.js‛></script>
<body>
[ … ]
</body>
</html>
scripts/main.js
require([‚coffee/machine‛], function (CoffeeMachine) {
coffeeMachine = new CoffeeMachine();
coffeeMachine.ui.show();
});
Asynchronous Module
Definitions (AMD)
AMD Benefits
 Code internals are encapsulated, with explicitly exposed
interfaces
 Code is reusable as long as paths match or are aliased
 Dependencies are explicitly named
 Dependency loading is asynchronous, and can be done in
parallel
 Implemented in vanilla JavaScript only; no fundamental new
semantics
AMD Problems
 Lots of boilerplate (for JavaScript)
 Lots of complexity
 Can’t handle circular dependencies
 Can result in code that requires many HTTP requests to pull down its
large dependency network (solvable with R.js or similar)
CommonJS Modules
var $ = require(‚jquery‛);
var coffeeGrinder = require(‚./coffeeGrinder‛);
var niceBeans = require(‚./coffeeBeans‛).NICE_BEANS;
[… code to do something tenuously coffee related …]
exports.doSomethingCoffeeRelated = function () { … };
exports.usefulNumber = 4;
CommonJS Modules
var $ = require(‚jquery‛);
var coffeeGrinder = require(‚./coffeeGrinder‛);
var niceBeans = require(‚./coffeeBeans‛).NICE_BEANS;
[… code to do something tenuously coffee related …]
exports.doSomethingCoffeeRelated = function () { … };
exports.usefulNumber = 4;
CommonJS Modules
var $ = require(‚jquery‛);
var CoffeeGrinder = require(‚./coffeeGrinder‛).CoffeeGrinder;
var niceBeans = require(‚./coffeeBeans‛).NICE_BEANS;
[… code to do something tenuously coffee related …]
exports.doSomethingCoffeeRelated = function () { … };
exports.usefulNumber = 4;
CommonJS Runners
 Various non-browser platforms
 Browserify
 Require.js
CommonJS Runners
 Various non-browser platforms
 Node.JS, CouchDB, Narwhal, XULJet
 The native environment for CommonJS modules
 Synchronous loading makes perfect sense server-side
 Closer model to non-browser scripting languages
 Browserify
 Require.js
CommonJS Runners
 Various non-browser platforms
 Browserify
 CommonJS modules for the browser
 Build tool that takes CommonJS modules and compiles
the whole app into a single script file
 Lets node.js modules work directly in a browser
 Require.js
CommonJS Runners
 Various non-browser platforms
 Browserify
 Require.js
 Primarily an AMD script loader
 Can support CommonJS style modules, hackily, with:
define(function(require, exports) {
var beanTypes = require(‚coffeeMachine/beanTypes‛);
exports.favouriteBeanType = beanTypes[0];
});
CommonJS Benefits
 Code internals are encapsulated
 Dependencies are explicitly named
 Code is easily reusable
 Simple clean syntax and conceptual model
 Basically no boilerplate
 Handles circular references better than AMD
CommonJS Problems
 Lots of magic involved
 Doesn’t follow standard JavaScript conventions
 No consideration of environment where loads are expensive
 Ignores JavaScript’s inherent asynchronicity
 Dependencies aren’t necessarily all obvious upfront
ES6 Modules
module ‚aCoffeeComponent‛ {
import $ from ‘jquery’;
import { NICE_BEANS as niceBeans } from ‚beanTypes‛;
import ‘coffeeMachine/coffeeGrinder’ as grinder;
export default function doSomethingCoffeeRelated() { … };
export var usefulNumber = 4;
}
ES6 Modules
module ‚aCoffeeComponent‛ {
import $ from ‘jquery’;
import { NICE_BEANS as niceBeans } from ‚beanTypes‛;
import ‘coffeeMachine/coffeeGrinder’ as grinder;
export default function doSomethingCoffeeRelated() { … };
export var usefulNumber = 4;
}
ES6 Modules
module ‚aCoffeeComponent‛ {
import $ from ‘jquery’;
import { NICE_BEANS as niceBeans } from ‚beanTypes‛;
import ‘coffeeMachine/coffeeGrinder’ as grinder;
export default function doSomethingCoffeeRelated() { … };
export var usefulNumber = 4;
}
ES6 Modules
module ‚aCoffeeComponent‛ {
import $ from ‚jquery‛;
import { NICE_BEANS as niceBeans } from ‚beanTypes‛;
import ‘coffeeMachine/coffeeGrinder’ as grinder;
export default function doSomethingCoffeeRelated() { … };
export var usefulNumber = 4;
}
ES6 Module Benefits
 Likely to be extremely well supported everywhere, eventually
 More granular & powerful module import controls
 New syntax, but otherwise fairly true to existing JS semantics
 Fairly low on boilerplate
 Handles circular references even better
 Similar to other language concepts & syntax
 Modules can be declared either inline, or nested, or externally
ES6 Module Problems
 Currently supported effectively nowhere
 Not even final in the spec yet
 Quite a lot of genuinely new syntax
 import * is included, but is frowned upon in every other language
 Powerful, but thereby comparatively quite complicated
Which one do I use?
IIFE:
For tiny projects
For trivial
compatibility
AMD:
For most serious
browser-based
projects
For a no-build
pure-JS solution
If you need to
depend on non-JS
content/events
CommonJS:
For anything
outside a browser
environment
For anything in a
browser where
you might want
Node modules
ES6:
If you yearn for
the extremely
bleeding edge
And you live way
in the future
where it has real
support
Thank you
Tim Perry
Tech Lead & Open-Source Champion at Softwire
@pimterry / github.com/pimterry / tim-perry.co.uk

More Related Content

What's hot

Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011Manuel Carrasco Moñino
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Jeado Ko
 
Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0Jeado Ko
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackNelson Glauber Leal
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 

What's hot (20)

Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
 
AngularJs
AngularJsAngularJs
AngularJs
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Backbone js
Backbone jsBackbone js
Backbone js
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Why ruby
Why rubyWhy ruby
Why ruby
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com Jetpack
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Web components
Web componentsWeb components
Web components
 

Similar to The Many Ways to Build Modular JavaScript

ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC InternalsVitaly Baum
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CNjojule
 
Mozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSMozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSRobert Nyman
 
Building Isomorphic Apps (JSConf.Asia 2014)
Building Isomorphic Apps (JSConf.Asia 2014)Building Isomorphic Apps (JSConf.Asia 2014)
Building Isomorphic Apps (JSConf.Asia 2014)Spike Brehm
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'sAntônio Roberto Silva
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen LjuSkills Matter
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen LjuSkills Matter
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?Remy Sharp
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 

Similar to The Many Ways to Build Modular JavaScript (20)

ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC Internals
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
 
Mozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSMozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJS
 
Building Isomorphic Apps (JSConf.Asia 2014)
Building Isomorphic Apps (JSConf.Asia 2014)Building Isomorphic Apps (JSConf.Asia 2014)
Building Isomorphic Apps (JSConf.Asia 2014)
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
ParisJS #10 : RequireJS
ParisJS #10 : RequireJSParisJS #10 : RequireJS
ParisJS #10 : RequireJS
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
jQuery
jQueryjQuery
jQuery
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
JavaScript on the Desktop
JavaScript on the DesktopJavaScript on the Desktop
JavaScript on the Desktop
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

The Many Ways to Build Modular JavaScript

  • 1. The Many Ways to Build Modular JavaScript Tim Perry Tech Lead & Open-Source Champion at Softwire @pimterry / github.com/pimterry / tim-perry.co.uk
  • 2. JavaScript  Originally designed by Brendan Eich for Netscape in mid-1995 as LiveScript, based on his ideas from Scheme and Self, and implemented over 10 days ‘or something worse than JS would have happened’.  LiveScript ships in Netscape 2.0 that September  Renamed to JavaScript three months later to confuse as many people as possible for marketing purposes  Standardisation begins a year later (now as ECMAScript), after everybody has already implemented their own unique take.  First ECMAScript spec is published in June 1997.  16 years later, it’s the de facto standard language for all code on the largest common platform in the world (and everybody still calls it JavaScript)
  • 3.
  • 4. JavaScript Some great bits:  Dynamic typing  First-order functions & closures Some features that just need removing:  The ‘with’ keyword  Much of type coercion  Automatic semicolon insertion Some fundamental structures that are hugely counter-intuitive:  How ‘this’ and variable scope work  Prototypes Some clearly relevant features that don’t exist:  Simple class definitions  Tail-call optimizations  A mechanism to allow structured modular code
  • 5. Why? coffeeFunctions.js: function askAboutSugar() { … } function askAboutMilk() { … } function prepareMug(sugar, milk) { … } function requestuserEmptyGrounds() { … } function requestuserEmptyTray() { … } function grindBeans() { … } function putGroundsInFilter() { … } function heatWater() { … } function waterHotEnough() { … } function pourCoffeeInMug () { … } function serveMugToUser() { … } index.html: <html><body> <button onclick=‚makeCoffee()‛>Make Coffee</button> <script src=‚coffeeFunctions.js‛></script> <script> function makeCoffee() { var sugars = askAboutSugar(); var milk = askAboutMilk(); prepareMug(sugars, milk); while (!groundsAreEmpty) requestUserEmptyGrounds(); while (!dripTrayIsEmpty) requestUserEmptyTray(); grindBeans(); putGroundsInFilter(); heatWater(); while (!waterHotEnough()) wait(); pourCoffeeInMug(); serveMugToUser(); }; </script> </body></html>
  • 6. Why? JavaScript uses lexically-defined function scoping Variables definitions are either in local scope or global scope function f() { var localVar = ‚a string‛; } function f(localParameter) { localParameter = ‚a string‛; } function f() { function localFunction() { } } var globalVar = ‚a string‛; function g() { globalVar = ‚a string‛; } function g() { window.globalVar = ‚a string‛; } window.window.window.window === window;
  • 7. Why? index.html: <html><body> <button onclick=‚makeCoffee()‛>Make Coffee</button> <script src=‚coffeeFunctions.js‛></script> <script> function makeCoffee() { var sugars = askAboutSugar(); var milk = askAboutMilk(); prepareMug(sugars, milk); while (!groundsAreEmpty) requestUserEmptyGrounds(); while (!dripTrayIsEmpty) requestUserEmptyTray(); grindBeans(); putGroundsInFilter(); heatWater(); while (!waterHotEnough()) wait(); pourCoffeeInMug(); serveMugToUser(); }; </script> </body></html> coffeeFunctions.js: function askAboutSugar() { … } function askAboutMilk() { … } function prepareMug(sugar, milk) { … } function requestuserEmptyGrounds() { … } function requestuserEmptyTray() { … } function grindBeans() { … } function putGroundsInFilter() { … } function heatWater() { … } function waterHotEnough() { … } function pourCoffeeInMug() { … } function serveMugToUser() { … }
  • 8. Why? index.html: <html><body> <button onclick=‚makeCoffee()‛>Make Coffee</button> <script src=‚coffeeFunctions.js‛></script> <script> function makeCoffee() { var sugars = askAboutSugar(); var milk = askAboutMilk(); prepareMug(sugars, milk); while (!groundsAreEmpty) requestUserEmptyGrounds(); while (!dripTrayIsEmpty) requestUserEmptyTray(); grindBeans(); putGroundsInFilter(); heatWater(); while (!waterHotEnough()) wait(); pourCoffeeInMug(); serveMugToUser(); }; </script> </body></html> coffeeFunctions.js: function askAboutSugar() { … } function askAboutMilk() { … } function prepareMug(sugar, milk) { … } function requestuserEmptyGrounds() { … } function requestuserEmptyTray() { … } function grindBeans() { … } function putGroundsInFilter() { … } function heatWater() { … } function waterHotEnough() { … } function pourCoffeeInMug() { stopHeatingWater(); openCoffeeTap(); pourWaterThroughFilter(); } function serveMugToUser() { … }
  • 9. Why? Global state makes systems hard to reason about
  • 10. Why? Encapsulation breaks systems into component parts, which can be clearly reasoned about
  • 11. index.html: <html> <body> <button>Make Coffee</button> <script src=‚beanGrinder.js‛></script> <script src=‚hotWaterSource.js‛></script> <script src=‚coffeeMachineUi.js‛></script> <script src=‚coffeeController.js‛></script> <script src=‚coffeeMachine.js‛></script> <script> coffeeMachine = new CoffeeMachine(); coffeeMachine.ui.show(); </script> </body> </html> Why? coffeeMachine.js: function CoffeeMachine() { var grinder = new BeanGrinder(); var hotWater = new HotWaterSource(); var ui = new CoffeeMachineUi(); var cc = new CoffeeController(grinder, hotWater, ui); } beanGrinder.js: function BeanGrinder() { … } coffeeController.js: function CoffeeController(grinder, hotWater, ui) { … } hotWaterSource.js: function HotWaterSource() { … }
  • 13. Why? beanGrinder.js: function BeanGrinder() { var beans = ko.observable(new BeanSupply()); var grindStrategy = new GrindStrategy(); this.grindBeans = function () { … }; } coffeeMachineUi.js: function CoffeeMachineUi() { this.onMakeCoffee = function (makeCoffeeCallback) { $(‚button‛).click(makeCoffeeCallback); $(‚beanTypes‛).draggable(); }; this.askForSugar = function () { … }; this.askForMilk = function () { … }; this.confirmCancelMyCoffeePlease = function () { … }; } hotWaterSource.js: function HotWaterSource() { var dynamicsCalculator = new FluidCalc(); this.openTap = function () { … } this.startHeating = function () { … } this.stopHeating = function () { … } }
  • 14. Why? beanGrinder.js: function BeanGrinder() { var beans = ko.observable(new BeanSupply()); var grindStrategy = new GrindStrategy(); this.grindBeans = function () { … }; } coffeeMachineUi.js: function CoffeeMachineUi() { this.onMakeCoffee = function (makeCoffeeCallback) { $(‚button‛).click(makeCoffeeCallback); $(‚beanTypes‛).draggable(); }; this.askForSugar = function () { … }; this.askForMilk = function () { … }; this.confirmCancelMyCoffeePlease = function () { … }; } hotWaterSource.js: function HotWaterSource() { var dynamicsCalculator = new FluidCalc(); this.openTap = function () { … } this.startHeating = function () { … } this.stopHeating = function () { … } }
  • 15. index.html: <html><body> <script src=‚jquery.js‛></script> <script src=‚jquery-ui.js‛></script> <script src=‚knockout.js‛></script> <script src=‚beanSupply.js‛></script> <script src=‚grindStrategy.js‛></script> <script src=‚fluidDynamicsLib.js‛></script> <script src=‚beanGrinder.js‛></script> <script src=‚coffeeMachineUi.js‛></script> <script src=‚coffeeController.js‛></script> <script src=‚hotWaterSource.js‛></script> <script src=‚coffeeMachine.js‛></script> <script> coffeeMachine = new CoffeeMachine(); coffeeMachine.ui.show(); </script> </body></html> Why?
  • 16. Why? Be explicit about your component’s external dependencies
  • 17. Why? 1. Encapsulated state 2. Reusable code 3. Explicit dependency management
  • 18. Immediately-Invoked Function Expression (IIFE) window.coffeeMachine.moduleName = (function ($, grindStrategy) { [… some code using these dependencies…] return aModuleObject; })(window.jQuery, window.coffeeMachine.grindStrategy);
  • 19. Immediately-Invoked Function Expression (IIFE) window.coffeeMachine.moduleName = (function ($, grindStrategy) { [… some code using these dependencies…] return aModuleObject; })(window.jQuery, window.coffeeMachine.grindStrategy);
  • 20. Immediately-Invoked Function Expression (IIFE) window.coffeeMachine.moduleName = (function ($, grindStrategy) { [… some code using these dependencies…] return aModuleObject; })(window.jQuery, window.coffeeMachine.grindStrategy);
  • 21. Immediately-Invoked Function Expression (IIFE) window.coffeeMachine.moduleName = (function ($, grindStrategy) { [… some code using these dependencies…] return aModuleObject; })(window.jQuery, window.coffeeMachine.grindStrategy);
  • 22. Immediately-Invoked Function Expression (IIFE) window.coffeeMachine.moduleName = (function ($, grindStrategy) { [… some code using these dependencies…] return aModuleObject; })(window.jQuery, window.coffeeMachine.grindStrategy);
  • 23. IIFE Module Benefits  Code internals are encapsulated  Dependencies are explicitly named  Code is reusable (in contexts where the dependencies are already available)
  • 24. IIFE Module Problems  Global state has to be used to store each module exported from an IIFE module  Namespacing requires manual initialization and management  Module loading and ordering still have to be managed manually
  • 25. Asynchronous Module Definitions (AMD) define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛], function ($, ko, coffeeGrinder) { [… make coffee or build some private state or something …] return { ‚doSomethingCoffeeRelated‛ : coffeeMakingFunction, ‚usefulNumber‛ : 4, }; } );
  • 26. Asynchronous Module Definitions (AMD) define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛], function ($, ko, coffeeGrinder) { [… make coffee or build some private state or something …] return { ‚doSomethingCoffeeRelated‛ : coffeeMakingFunction, ‚usefulNumber‛ : 4, }; } );
  • 27. Asynchronous Module Definitions (AMD) define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛], function ($, ko, coffeeGrinder) { [… make coffee or build some private state or something …] return { ‚doSomethingCoffeeRelated‛ : coffeeMakingFunction, ‚usefulNumber‛ : 4, }; } );
  • 28. Asynchronous Module Definitions (AMD) define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛], function ($, ko, coffeeGrinder) { [… make coffee or build some private state or something …] return { ‚doSomethingCoffeeRelated‛ : coffeeMakingFunction, ‚usefulNumber‛ : 4, }; } );
  • 29. Asynchronous Module Definitions (AMD) define([‚lib/jquery‛, ‚lib/knockout‛, ‚coffeeMachine/grinder‛], function ($, ko, coffeeGrinder) { [… make coffee or build some private state or something …] return { ‚doSomethingCoffeeRelated‛ : coffeeMakingFunction, ‚usefulNumber‛ : 4, }; } );
  • 30. Asynchronous Module Definitions (AMD) require([‚font!fonts/myFavFont‛, ‚less!styles/homeStyle‛, ‚domReady!‛], function () { showPageNowThatAllPrerequisitesAreLoaded(); } );
  • 31. Asynchronous Module Definitions (AMD) require([‚font!fonts/myFavFont‛, ‚less!styles/homeStyle‛, ‚domReady!‛], function () { showPageNowThatAllPrerequisitesAreLoaded(); } );
  • 32. index.html: <html> <script src=‚require.js‛ data-main=‚scripts/main.js‛></script> <body> [ … ] </body> </html> scripts/main.js require([‚coffee/machine‛], function (CoffeeMachine) { coffeeMachine = new CoffeeMachine(); coffeeMachine.ui.show(); }); Asynchronous Module Definitions (AMD)
  • 33. AMD Benefits  Code internals are encapsulated, with explicitly exposed interfaces  Code is reusable as long as paths match or are aliased  Dependencies are explicitly named  Dependency loading is asynchronous, and can be done in parallel  Implemented in vanilla JavaScript only; no fundamental new semantics
  • 34. AMD Problems  Lots of boilerplate (for JavaScript)  Lots of complexity  Can’t handle circular dependencies  Can result in code that requires many HTTP requests to pull down its large dependency network (solvable with R.js or similar)
  • 35. CommonJS Modules var $ = require(‚jquery‛); var coffeeGrinder = require(‚./coffeeGrinder‛); var niceBeans = require(‚./coffeeBeans‛).NICE_BEANS; [… code to do something tenuously coffee related …] exports.doSomethingCoffeeRelated = function () { … }; exports.usefulNumber = 4;
  • 36. CommonJS Modules var $ = require(‚jquery‛); var coffeeGrinder = require(‚./coffeeGrinder‛); var niceBeans = require(‚./coffeeBeans‛).NICE_BEANS; [… code to do something tenuously coffee related …] exports.doSomethingCoffeeRelated = function () { … }; exports.usefulNumber = 4;
  • 37. CommonJS Modules var $ = require(‚jquery‛); var CoffeeGrinder = require(‚./coffeeGrinder‛).CoffeeGrinder; var niceBeans = require(‚./coffeeBeans‛).NICE_BEANS; [… code to do something tenuously coffee related …] exports.doSomethingCoffeeRelated = function () { … }; exports.usefulNumber = 4;
  • 38. CommonJS Runners  Various non-browser platforms  Browserify  Require.js
  • 39. CommonJS Runners  Various non-browser platforms  Node.JS, CouchDB, Narwhal, XULJet  The native environment for CommonJS modules  Synchronous loading makes perfect sense server-side  Closer model to non-browser scripting languages  Browserify  Require.js
  • 40. CommonJS Runners  Various non-browser platforms  Browserify  CommonJS modules for the browser  Build tool that takes CommonJS modules and compiles the whole app into a single script file  Lets node.js modules work directly in a browser  Require.js
  • 41. CommonJS Runners  Various non-browser platforms  Browserify  Require.js  Primarily an AMD script loader  Can support CommonJS style modules, hackily, with: define(function(require, exports) { var beanTypes = require(‚coffeeMachine/beanTypes‛); exports.favouriteBeanType = beanTypes[0]; });
  • 42. CommonJS Benefits  Code internals are encapsulated  Dependencies are explicitly named  Code is easily reusable  Simple clean syntax and conceptual model  Basically no boilerplate  Handles circular references better than AMD
  • 43. CommonJS Problems  Lots of magic involved  Doesn’t follow standard JavaScript conventions  No consideration of environment where loads are expensive  Ignores JavaScript’s inherent asynchronicity  Dependencies aren’t necessarily all obvious upfront
  • 44. ES6 Modules module ‚aCoffeeComponent‛ { import $ from ‘jquery’; import { NICE_BEANS as niceBeans } from ‚beanTypes‛; import ‘coffeeMachine/coffeeGrinder’ as grinder; export default function doSomethingCoffeeRelated() { … }; export var usefulNumber = 4; }
  • 45. ES6 Modules module ‚aCoffeeComponent‛ { import $ from ‘jquery’; import { NICE_BEANS as niceBeans } from ‚beanTypes‛; import ‘coffeeMachine/coffeeGrinder’ as grinder; export default function doSomethingCoffeeRelated() { … }; export var usefulNumber = 4; }
  • 46. ES6 Modules module ‚aCoffeeComponent‛ { import $ from ‘jquery’; import { NICE_BEANS as niceBeans } from ‚beanTypes‛; import ‘coffeeMachine/coffeeGrinder’ as grinder; export default function doSomethingCoffeeRelated() { … }; export var usefulNumber = 4; }
  • 47. ES6 Modules module ‚aCoffeeComponent‛ { import $ from ‚jquery‛; import { NICE_BEANS as niceBeans } from ‚beanTypes‛; import ‘coffeeMachine/coffeeGrinder’ as grinder; export default function doSomethingCoffeeRelated() { … }; export var usefulNumber = 4; }
  • 48. ES6 Module Benefits  Likely to be extremely well supported everywhere, eventually  More granular & powerful module import controls  New syntax, but otherwise fairly true to existing JS semantics  Fairly low on boilerplate  Handles circular references even better  Similar to other language concepts & syntax  Modules can be declared either inline, or nested, or externally
  • 49. ES6 Module Problems  Currently supported effectively nowhere  Not even final in the spec yet  Quite a lot of genuinely new syntax  import * is included, but is frowned upon in every other language  Powerful, but thereby comparatively quite complicated
  • 50. Which one do I use? IIFE: For tiny projects For trivial compatibility AMD: For most serious browser-based projects For a no-build pure-JS solution If you need to depend on non-JS content/events CommonJS: For anything outside a browser environment For anything in a browser where you might want Node modules ES6: If you yearn for the extremely bleeding edge And you live way in the future where it has real support
  • 51. Thank you Tim Perry Tech Lead & Open-Source Champion at Softwire @pimterry / github.com/pimterry / tim-perry.co.uk