RequireJS



Prathamesh Satpute

@prathamesh7pute

What is RequireJS ?


  • Javascript Module loader library
  • Supports asynchronous script loading and dependency management
  • Includes optimization and build tool r.js

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

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>

Performance

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

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;
});

Shims


shim: {
      underscore: {
          exports: '_'
      },
      backbone: {
          deps: ['underscore', 'jquery'],
          exports: 'Backbone'
      }
  }

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',
  }
});
// Start the main app logic.
require(['jquery', 'backbone', 'views/app'], function ($, Backbone, AppView) {
  // Initialize the application view
  new AppView();
});

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"
})

Thank You

Resources


RequireJS

Almond JS

Writing Modular JavaScript