• Save
The Many Ways to Build Modular JavaScript
Upcoming SlideShare
Loading in...5
×
 

The Many Ways to Build Modular JavaScript

on

  • 1,045 views

 

Statistics

Views

Total Views
1,045
Views on SlideShare
1,020
Embed Views
25

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 25

http://lanyrd.com 25

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

The Many Ways to Build Modular JavaScript The Many Ways to Build Modular JavaScript Presentation Transcript

  • 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