Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RequireJS

 RequireJS

Prathamesh Satpute

April 18, 2013
Tweet

Transcript

  1. WHAT IS REQUIREJS ? Javascript Module loader library Supports asynchronous

    script loading and dependency management Includes optimization and build tool r.js
  2. PROBLEM As web application gets bigger code complexity grows Number

    of script files get increases HTTP calls increases which reduces the performance of app Managing multiple script files and order of their inclusion becomes problematic Pollutes the global scope Assembly of web application gets harder
  3. DEPENDENCIES AND ORDER <script src="js/lib/jquery.js" type="text/javascript"></script> <script src="js/lib/underscore.js" type="text/javascript"></script> <script

    src="js/lib/backbone.js" type="text/javascript"></script> <script src="js/models/todo.js" type="text/javascript"></script> <script src="js/collections/todos.js" type="text/javascript"></script> <script src="js/views/todoView.js" type="text/javascript"></script> <script src="js/views/app.js" type="text/javascript"></script>
  4. SOLUTION 1. Front-end developers need something like #include/import/require 2. Optimization

    tool which takes care of resolving dependencies and script minification 3. Modular approach with the JavaScript Code
  5. MODULES define(['jquery','underscore','backbone','collections/todos'], function($, _, Backbone, Todos) { var AppView =

    Backbone.View.extend({ el: '#todo', events: { 'click #addTodo': 'newTodo' }, initialize: function () {...}, render: function () {...}, newTodo: function () {...} }); return AppView; });
  6. SHIMS shim: { underscore: { exports: '_' }, backbone: {

    deps: ['underscore', 'jquery'], exports: 'Backbone' } }
  7. CONFIGURATION <script data-main="scripts/main" src="scripts/require.js"></script> requirejs.config({ // The shim config allows

    us to configure dependencies for // scripts that do not call define() to register a module shim: { underscore: { exports: '_' }, backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' } }, paths: { jquery: 'lib/jquery', underscore: 'lib/underscore', backbone: 'lib/backbone/backbone', } });
  8. OPTIMIZATION node r.js -o baseUrl=. paths.jquery=some/other/jquery name=main out=main-built.js node r.js

    -o cssIn=main.css out=main-built.css node r.js -o build.js ({ baseUrl: ".", paths: { jquery: "some/other/jquery" }, name: "main", out: "main-built.js" })