Dependency Management with RequireJS

A
DEPENDENCY	
  	
  
MANAGEMENT	
  
with	
  RequireJS	
  
HELLO	
  
                              my	
  name	
  is	
  


         Aaron Hardy
                                    ·∙	
  
                   @AARONIUS	
  	
  	
  	
  	
  AARONHARDY.COM	
  


So8ware	
  Engineer,	
  Adobe	
  Digital	
  MarkeAng	
  Suite	
  
     We	
  enable	
  management,	
  measurement,	
  execu1on,	
  and	
  
       op1miza1on	
  of	
  digital	
  adver1sing	
  and	
  marke1ng.	
  
What	
  is	
  dependency	
  management?	
  
Loading…	
  
The	
  right	
  code.	
  
In	
  the	
  right	
  order.	
  
At	
  the	
  right	
  Ame.	
  
At	
  the	
  right	
  speed.	
  
	
  
(oh	
  and	
  btw,	
  make	
  it	
  easy)	
  
	
  
	
  
Old-­‐school	
  Dependency	
  Management	
  
What	
  are	
  the	
  dependencies	
  here?	
  
<script     src="script3.js"></script>
<script     src="script1.js"></script>
<script     src="script13.js"></script>
<script     src="script7.js"></script>
<script     src="script6.js"></script>
<script     src="script12.js"></script>
<script     src="script4.js"></script>
<script     src="script11.js"></script>
<script     src="script5.js"></script>
<script     src="script9.js"></script>
<script     src="script8.js"></script>
<script     src="script10.js"></script>
<script     src="script2.js"></script>
Old-­‐school	
  Dependency	
  Management	
  
What	
  is	
  a	
  module?	
  
A	
  structure	
  used	
  to	
  encapsulate	
  methods	
  and	
  aTributes	
  to	
  avoid	
  
polluAng	
  the	
  global	
  namespace.	
  
var Calculator = (function(){
  function funkify(num) {
    return num * Math.random() / Math.random();
  }

   function add(a, b, getFunky){
     var sum = a + b;
     return getFunky ? funkify(sum) : sum;
   }

  return {
     add:add
  };
})();
What	
  is	
  AMD?	
  
Asynchronous	
  module	
  definiAon.	
  	
  	
  
•  A	
  mechanism	
  for	
  defining	
  modules	
  such	
  that	
  the	
  module	
  and	
  its	
  
   dependencies	
  can	
  be	
  asynchronously	
  loaded.	
  
•  Suited	
  for	
  a	
  browser	
  environment.	
  
•  Generally	
  used	
  in	
  tandem	
  with	
  an	
  AMD	
  loader.	
  
What	
  is	
  RequireJS?	
  
A	
  JavaScript	
  file	
  and	
  module	
  loader.	
  Capable	
  of	
  loading	
  modules	
  
defined	
  in	
  the	
  AMD	
  format	
  and	
  their	
  dependencies.	
  
	
  
Not	
  the	
  only	
  AMD	
  loader	
  (but	
  unofficially	
  the	
  most	
  popular)	
  
•  curl.js	
  
•  lsjs	
  
•  dojo	
  
•  mootools	
  
	
  
Open	
  source.	
  New	
  BSD	
  or	
  MIT	
  licensed.	
  
Defining	
  a	
  module 	
  	
  
/js/book.js	
  
define({
  title: "My Sister's Keeper",
  publisher: "Atria"
});
RequesAng	
  dependencies	
  
/js/bookshelf.js	
  
define([
  'book'
], function(book) {
  return {
     listBook: function() {
       alert(book.title);
     }
  };
});
Se]ng	
  up	
  your	
  app	
  
/index.html	
  
<!DOCTYPE html>
<html>
  <head>
    <title>RequireJS Example</title>
    <script data-main="js/main"
         src="js/libs/require.js"></script>
  </head>
  <body/>
</html>
Se]ng	
  up	
  your	
  app	
  
/js/main.js	
  
require([
  'bookshelf'
], function(bookshelf) {
  bookshelf.listBook();
});
define()	
  vs.	
  require()	
  
define()	
  completes	
  three	
  steps:	
  
1.  Loads	
  the	
  specified	
  dependencies	
  
2.  Calls	
  the	
  callback	
  funcAon	
  
3.  Registers	
  the	
  return	
  value	
  from	
  the	
  callback	
  funcAon	
  

require()	
  only	
  performs	
  #1	
  and	
  #2.	
  
DEMO	
  
hTp://code.aaronhardy.com/require-­‐literal	
  
Defining	
  a	
  constructor	
  module 	
  	
  
/js/book.js	
  
define(function() {
  var Book = function(title, publisher) {
     this.title = title;
     this.publisher = publisher;
  };
  return Book;
});
Using	
  a	
  constructor	
  module 	
  	
  
/js/bookshelf.js	
  
define([
  'book'
], function(Book) {
  var books = [
     new Book('A Tale of Two Cities', 'Chapman & Hall'),
     new Book('The Good Earth', 'John Day')
  ];

  return {
     listBooks: function() {
       for (var i = 0, ii = books.length; i < ii; i++) {
         alert(books[i].title);
       }
     }
  };
});
DEMO	
  
hTp://code.aaronhardy.com/require-­‐constructor	
  
Configuring	
  RequireJS	
  
/js/main.js	
  
require.config({
  baseUrl: '/another/path',
  paths: {
    'myModule': 'dirA/dirB/dirC/dirD/myModule’,
    'templates': '../templates',
    'text': 'libs/text'
  }
});

require([
  'bookshelf'
], function(bookshelf) {
  bookshelf.listBook();
});
Shimming	
  non-­‐AMD	
  libraries	
  
/js/main.js	
  
require.config({
  paths: {
     jquery: 'libs/jquery',
     underscore': 'libs/lodash',
     backbone: 'libs/backbone',
  },
  shim: {
     backbone: {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
     },
     underscore: {
        exports: '_’
     }
  }
});
Using	
  shimmed	
  libraries	
  
/js/book.js	
  
define([
  'backbone'
], function(Backbone) {
  return Backbone.Model.extend({
     defaults: {
       genre: 'historical'
     }
  })
});
RequireJS	
  plugins	
  
Used	
  for	
  loading	
  and/or	
  transforming	
  different	
  types	
  of	
  
dependencies	
  either	
  at	
  run-­‐Ame	
  or	
  compile-­‐Ame.	
  
•  text	
  –	
  Loads	
  files	
  as	
  plain	
  text	
  
•  i18n	
  –	
  InternaAonalizaAon	
  
•  cs	
  –	
  Loads	
  and	
  compiles	
  CoffeeScript	
  
•  font	
  –	
  Loads	
  web	
  fonts	
  
•  image	
  –	
  Loads	
  image	
  files	
  
•  json	
  –	
  Loads	
  and	
  parses	
  JSON	
  
•  mdown	
  –	
  Loads	
  and	
  compiles	
  Markdown	
  
	
  
and	
  many	
  more…	
  

	
  
RequireJS	
  text	
  plugin	
  usage	
  
/js/main.js	
  
require.config({
  'paths': {
    'jquery': 'libs/jquery',
    'templates': '../templates',
    'text': 'libs/text’
  }
});

require([
  'jquery',
  'text!templates/book.tpl.html'
], function($, template) {
  $(document).ready(function() {
    $('body').html(template);
  });
});
DEMO	
  
hTp://code.aaronhardy.com/require-­‐template	
  
CondiAonal	
  dependencies	
  
require([
  'modernizr'
], function(Modernizr) {
  var drawCircle = function() { … };

  if (Modernizr.canvas) {
    drawCircle();
  } else {
    require(['excanvas'], drawCircle);
  }
});
Errbacks	
  
requirejs.config({
  enforceDefine: true,
  paths: {
    jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
  }
});

require(['jquery'], function ($) {
  //Do something with $ here
}, function (err) {
  var failedId = err.requireModules && err.requireModules[0],
  if (failedId === 'jquery') {
    requirejs.undef(failedId);

      requirejs.config({
        paths: {
          jquery: 'local/jquery'
        }
      });

      require(['jquery'], function () {});
  }
});
OpAmizaAon	
  
ConcatenaAon	
  and	
  minificaAon	
  
r.js	
  –	
  RequireJS	
  opAmizer	
  able	
  to	
  run	
  in	
  Node	
  or	
  Rhino	
  (Java)	
  
DEMO	
  
hTp://code.aaronhardy.com/require-­‐opAmizaAon	
  
node	
  libs/r.js	
  -­‐o	
  baseUrl=.	
  name=main	
  out=main-­‐built.js	
  
OpAmizaAon	
  using	
  almond	
  
In	
  producAon,	
  replaces	
  RequireJS	
  and	
  is	
  bundled	
  with	
  built	
  file.	
  
•  1K	
  (almond)	
  vs	
  14K	
  (RequireJS)	
  
•  Avoids	
  two	
  separate,	
  sequenAal	
  HTTP	
  requests	
  
	
  
Biggest	
  limitaAon:	
  
•  No	
  dynamic	
  loading;	
  all	
  dependencies	
  must	
  be	
  in	
  the	
  same	
  file	
  or	
  
      loaded	
  beforehand	
  


	
  
DEMO	
  
hTp://code.aaronhardy.com/require-­‐almond	
  
node	
  libs/r.js	
  -­‐o	
  baseUrl=.	
  name=libs/almond	
  include=main	
  out=main-­‐built.js	
  
THANK	
  YOU!	
  
@aaronius	
  ·∙	
  aaronhardy.com	
  
1 of 30

Recommended

JavaScript for Flex Devs by
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
9.2K views80 slides
Angular JS blog tutorial by
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
4.3K views43 slides
AngularJS Directives by
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
11.9K views38 slides
DrupalCon jQuery by
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQueryNathan Smith
1.8K views55 slides
Styling components with JavaScript by
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScriptbensmithett
11.2K views38 slides
Drupal Development (Part 2) by
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
2.1K views79 slides

More Related Content

What's hot

Modular and Event-Driven JavaScript by
Modular and Event-Driven JavaScriptModular and Event-Driven JavaScript
Modular and Event-Driven JavaScriptEduardo Shiota Yasuda
19.3K views162 slides
AngularJS Basics with Example by
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with ExampleSergey Bolshchikov
42.4K views26 slides
Angular Directives from Scratch by
Angular Directives from ScratchAngular Directives from Scratch
Angular Directives from ScratchChristian Lilley
5.8K views88 slides
Viking academy backbone.js by
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
860 views31 slides
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점 by
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Jeado Ko
2.2K views64 slides
Arquitetura de Front-end em Aplicações de Larga Escala by
Arquitetura de Front-end em Aplicações de Larga EscalaArquitetura de Front-end em Aplicações de Larga Escala
Arquitetura de Front-end em Aplicações de Larga EscalaEduardo Shiota Yasuda
3K views108 slides

What's hot(20)

Viking academy backbone.js by Bert Wijnants
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Bert Wijnants860 views
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점 by Jeado Ko
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko2.2K views
AngularJS Internal by Eyal Vardi
AngularJS InternalAngularJS Internal
AngularJS Internal
Eyal Vardi7.9K views
[FEConf Korea 2017]Angular 컴포넌트 대화법 by Jeado Ko
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko2.4K views
Drupal Development by Jeff Eaton
Drupal DevelopmentDrupal Development
Drupal Development
Jeff Eaton8.6K views
Bootstrap과 UI-Bootstrap by WebFrameworks
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-Bootstrap
WebFrameworks655 views
Introduction to javascript templating using handlebars.js by Mindfire Solutions
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.js
Mindfire Solutions2.8K views
Backbone.js and friends by Good Robot
Backbone.js and friendsBackbone.js and friends
Backbone.js and friends
Good Robot1.1K views
AngularJS Routing by Eyal Vardi
AngularJS RoutingAngularJS Routing
AngularJS Routing
Eyal Vardi10.1K views
Django Admin: Widgetry & Witchery by Pamela Fox
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & Witchery
Pamela Fox2.3K views
날로 먹는 Django admin 활용 by KyeongMook "Kay" Cha
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
HTML5: where flash isn't needed anymore by Remy Sharp
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
Remy Sharp2.5K views
WebApps e Frameworks Javascript by meet2Brains
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascript
meet2Brains791 views

Similar to Dependency Management with RequireJS

How and why i roll my own node.js framework by
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
3.3K views62 slides
SproutCore and the Future of Web Apps by
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
708 views80 slides
JS-05-Handlebars.ppt by
JS-05-Handlebars.pptJS-05-Handlebars.ppt
JS-05-Handlebars.pptfakeaccount225095
4 views19 slides
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016 by
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
431 views26 slides
Javascript first-class citizenery by
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
1.2K views32 slides
Drupal & javascript by
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
4.8K views53 slides

Similar to Dependency Management with RequireJS(20)

How and why i roll my own node.js framework by Ben Lin
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin3.3K views
SproutCore and the Future of Web Apps by Mike Subelsky
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
Mike Subelsky708 views
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016 by Nicolás Bouhid
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Nicolás Bouhid431 views
Javascript first-class citizenery by toddbr
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr1.2K views
Drupal & javascript by Almog Baku
Drupal & javascriptDrupal & javascript
Drupal & javascript
Almog Baku4.8K views
Beyond DOMReady: Ultra High-Performance Javascript by aglemann
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
aglemann2.7K views
jQuery & 10,000 Global Functions: Working with Legacy JavaScript by Guy Royse
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse1.7K views
Bonnes pratiques de développement avec Node js by Francois Zaninotto
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto5.7K views
jQuery and Rails: Best Friends Forever by stephskardal
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
stephskardal24.9K views
[Coscup 2012] JavascriptMVC by Alive Kuo
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
Alive Kuo1.3K views
JQuery In Drupal by katbailey
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
katbailey3.8K views
JavaScript Growing Up by David Padbury
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury14.1K views
Writing HTML5 Web Apps using Backbone.js and GAE by Ron Reiter
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter12.2K views
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5) by Igor Bronovskyy
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy410 views

Recently uploaded

Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...ShapeBlue
88 views13 slides
Kyo - Functional Scala 2023.pdf by
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfFlavio W. Brasil
449 views92 slides
Network Source of Truth and Infrastructure as Code revisited by
Network Source of Truth and Infrastructure as Code revisitedNetwork Source of Truth and Infrastructure as Code revisited
Network Source of Truth and Infrastructure as Code revisitedNetwork Automation Forum
52 views45 slides
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsShapeBlue
197 views13 slides
20231123_Camunda Meetup Vienna.pdf by
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
50 views73 slides
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...ShapeBlue
132 views15 slides

Recently uploaded(20)

Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by ShapeBlue
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
ShapeBlue88 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue197 views
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue132 views
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by ShapeBlue
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
ShapeBlue154 views
Future of AR - Facebook Presentation by Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty62 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue210 views
Digital Personal Data Protection (DPDP) Practical Approach For CISOs by Priyanka Aash
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOs
Priyanka Aash153 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson156 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue163 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue176 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue98 views
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue112 views
NTGapps NTG LowCode Platform by Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu365 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue179 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue101 views
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue138 views

Dependency Management with RequireJS

  • 1. DEPENDENCY     MANAGEMENT   with  RequireJS  
  • 2. HELLO   my  name  is   Aaron Hardy ·∙   @AARONIUS          AARONHARDY.COM   So8ware  Engineer,  Adobe  Digital  MarkeAng  Suite   We  enable  management,  measurement,  execu1on,  and   op1miza1on  of  digital  adver1sing  and  marke1ng.  
  • 3. What  is  dependency  management?   Loading…   The  right  code.   In  the  right  order.   At  the  right  Ame.   At  the  right  speed.     (oh  and  btw,  make  it  easy)      
  • 4. Old-­‐school  Dependency  Management   What  are  the  dependencies  here?   <script src="script3.js"></script> <script src="script1.js"></script> <script src="script13.js"></script> <script src="script7.js"></script> <script src="script6.js"></script> <script src="script12.js"></script> <script src="script4.js"></script> <script src="script11.js"></script> <script src="script5.js"></script> <script src="script9.js"></script> <script src="script8.js"></script> <script src="script10.js"></script> <script src="script2.js"></script>
  • 6. What  is  a  module?   A  structure  used  to  encapsulate  methods  and  aTributes  to  avoid   polluAng  the  global  namespace.   var Calculator = (function(){ function funkify(num) { return num * Math.random() / Math.random(); } function add(a, b, getFunky){ var sum = a + b; return getFunky ? funkify(sum) : sum; } return { add:add }; })();
  • 7. What  is  AMD?   Asynchronous  module  definiAon.       •  A  mechanism  for  defining  modules  such  that  the  module  and  its   dependencies  can  be  asynchronously  loaded.   •  Suited  for  a  browser  environment.   •  Generally  used  in  tandem  with  an  AMD  loader.  
  • 8. What  is  RequireJS?   A  JavaScript  file  and  module  loader.  Capable  of  loading  modules   defined  in  the  AMD  format  and  their  dependencies.     Not  the  only  AMD  loader  (but  unofficially  the  most  popular)   •  curl.js   •  lsjs   •  dojo   •  mootools     Open  source.  New  BSD  or  MIT  licensed.  
  • 9. Defining  a  module     /js/book.js   define({ title: "My Sister's Keeper", publisher: "Atria" });
  • 10. RequesAng  dependencies   /js/bookshelf.js   define([ 'book' ], function(book) { return { listBook: function() { alert(book.title); } }; });
  • 11. Se]ng  up  your  app   /index.html   <!DOCTYPE html> <html> <head> <title>RequireJS Example</title> <script data-main="js/main" src="js/libs/require.js"></script> </head> <body/> </html>
  • 12. Se]ng  up  your  app   /js/main.js   require([ 'bookshelf' ], function(bookshelf) { bookshelf.listBook(); });
  • 13. define()  vs.  require()   define()  completes  three  steps:   1.  Loads  the  specified  dependencies   2.  Calls  the  callback  funcAon   3.  Registers  the  return  value  from  the  callback  funcAon   require()  only  performs  #1  and  #2.  
  • 15. Defining  a  constructor  module     /js/book.js   define(function() { var Book = function(title, publisher) { this.title = title; this.publisher = publisher; }; return Book; });
  • 16. Using  a  constructor  module     /js/bookshelf.js   define([ 'book' ], function(Book) { var books = [ new Book('A Tale of Two Cities', 'Chapman & Hall'), new Book('The Good Earth', 'John Day') ]; return { listBooks: function() { for (var i = 0, ii = books.length; i < ii; i++) { alert(books[i].title); } } }; });
  • 18. Configuring  RequireJS   /js/main.js   require.config({ baseUrl: '/another/path', paths: { 'myModule': 'dirA/dirB/dirC/dirD/myModule’, 'templates': '../templates', 'text': 'libs/text' } }); require([ 'bookshelf' ], function(bookshelf) { bookshelf.listBook(); });
  • 19. Shimming  non-­‐AMD  libraries   /js/main.js   require.config({ paths: { jquery: 'libs/jquery', underscore': 'libs/lodash', backbone: 'libs/backbone', }, shim: { backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, underscore: { exports: '_’ } } });
  • 20. Using  shimmed  libraries   /js/book.js   define([ 'backbone' ], function(Backbone) { return Backbone.Model.extend({ defaults: { genre: 'historical' } }) });
  • 21. RequireJS  plugins   Used  for  loading  and/or  transforming  different  types  of   dependencies  either  at  run-­‐Ame  or  compile-­‐Ame.   •  text  –  Loads  files  as  plain  text   •  i18n  –  InternaAonalizaAon   •  cs  –  Loads  and  compiles  CoffeeScript   •  font  –  Loads  web  fonts   •  image  –  Loads  image  files   •  json  –  Loads  and  parses  JSON   •  mdown  –  Loads  and  compiles  Markdown     and  many  more…    
  • 22. RequireJS  text  plugin  usage   /js/main.js   require.config({ 'paths': { 'jquery': 'libs/jquery', 'templates': '../templates', 'text': 'libs/text’ } }); require([ 'jquery', 'text!templates/book.tpl.html' ], function($, template) { $(document).ready(function() { $('body').html(template); }); });
  • 24. CondiAonal  dependencies   require([ 'modernizr' ], function(Modernizr) { var drawCircle = function() { … }; if (Modernizr.canvas) { drawCircle(); } else { require(['excanvas'], drawCircle); } });
  • 25. Errbacks   requirejs.config({ enforceDefine: true, paths: { jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min' } }); require(['jquery'], function ($) { //Do something with $ here }, function (err) { var failedId = err.requireModules && err.requireModules[0], if (failedId === 'jquery') { requirejs.undef(failedId); requirejs.config({ paths: { jquery: 'local/jquery' } }); require(['jquery'], function () {}); } });
  • 26. OpAmizaAon   ConcatenaAon  and  minificaAon   r.js  –  RequireJS  opAmizer  able  to  run  in  Node  or  Rhino  (Java)  
  • 27. DEMO   hTp://code.aaronhardy.com/require-­‐opAmizaAon   node  libs/r.js  -­‐o  baseUrl=.  name=main  out=main-­‐built.js  
  • 28. OpAmizaAon  using  almond   In  producAon,  replaces  RequireJS  and  is  bundled  with  built  file.   •  1K  (almond)  vs  14K  (RequireJS)   •  Avoids  two  separate,  sequenAal  HTTP  requests     Biggest  limitaAon:   •  No  dynamic  loading;  all  dependencies  must  be  in  the  same  file  or   loaded  beforehand    
  • 29. DEMO   hTp://code.aaronhardy.com/require-­‐almond   node  libs/r.js  -­‐o  baseUrl=.  name=libs/almond  include=main  out=main-­‐built.js  
  • 30. THANK  YOU!   @aaronius  ·∙  aaronhardy.com  

Editor's Notes

  1. node r.js -o name=main out=js/main-built.jsbaseUrl=js
  2. node r.js -o name=main out=js/main-built.jsbaseUrl=js