AngularJS With RequireJS

Introduction 

Require.js 
is a JavaScript file and module loader. It provides the ability to write JavaScript libraries that export a library and use the name of the module to set up a dependency, and it will be available when the module loads.

 
Its main benefits are given below: 
  • It keeps code more organized in a separate file.
  • It sets up an important process.
  • It can load nested dependencies.
  • It enables easy packaging dependencies.
RequrieJS uses Asynchronous Module Loading (AMD) technique for the loading of files. In the technique of AMD, each dependent module loads in the given order through an asynchronous way.

Why Require.js is required

One application with many JavaScript files has so many dependencies. Each file can be dependent on other JavaScript files.
Now, we want to load each file. So, we will have to manually specify the orders and dependency orders of files. We will have to remember dependency orders of which file will be loaded first. If we add a new Script file then we will have to check the order of files again. If sequence of file or dependency order is wrong then we will get an error. Application will not execute, so its a dependency complication.
 
So, we need a package for handling the dependency manager. It will manage the dependency of files for which file will be loaded in which manner. So, Require.js handles all these cases and it is very useful for managing dependencies.

You may not use Require.js if the following cases are there: 

  1. If application does not have many dependencies.
  2. If you don't care about the page load performance.
  3. If you don't like decoupled code.

Features of Require.js

  1. It is a package dependency manager.
  2. It is an Injector.
  3. JavaScript File Loader/ Lazy loading.
  4. Concatenate

Include Require.js into HTML file: 

We include Require.js as an HTML script tag like the following:
  1. <body>  
  2. <script src='require.js' data-main='init'></script>  
  3. </body>  
data-main: It tells require.js to load init.js file first.
So, we tell require.js about file dependencies into init.js file with the help of define(), require(), etc.

Import APIs of RequireJS: 

  1. define() - It defines dependencies and register factory function.
  2. require() - With require we just load / use a module or javascript file that can be loaded by require.js. Bascially, it is needed when we just want to load and use.
  3. config() - It configures source paths and alias.

define() 

It creates Asynchronous Module Definition (AMD), so files loaded in any order. It returns some value. With define() we register a module and other parts of application will depend on. So, it is used to define modules for using in multiple locations. It can return any type of value.
 
Syntax:
  1. define(id?, dependencies?, factory)  
Here, module id and dependencies arguments are optional.
 
Example:
 
1. Simple module defined as follows:
  1. define("Employee"function () {  
  2.     //You can name this function here,  
  3.     //which can help in debuggers but  
  4.     //has no impact on the module name.  
  5.     return function Employee(first, last) {  
  6.         this.first = first;   
  7.         this.last = last;  
  8.     };  
  9. });  
Now, use the "Employee" module into another module as follows: 
  1. define("main", ["Employee"], function (Employee) {  
  2.     var john = new Employee("John""Smith");  
  3. });  
2.
  1. // getUser.js  
  2. // Depends on a file (users.js), and returns a getUser function  
  3. define(['./users'], function(users) {  
  4.   return function getUser(username) {  
  5.     return users[username];  
  6.   };  
  7. });  
3. Let us have two dependencies:
  1. define(['myApp/users''myApp/myData'], function(users, myData) {  
  2.   return function getUser(username) {  
  3.     return users[username];  
  4.   };  
  5. });  

require() 

It just loads/uses one or more AMD module or JavaScript file. It acts as the initialization or ROOT of the dependency tree.
 
Syntax:
  1. require(Array, Function)  
Example:
 
It loads the myExample.js module from our first define() example.
  1. require(['./myExample.js'], function(myExample) {  
  2.   console.log('example.js return value: ', myExample);  
  3. });  
So, we should use both define and require. Basically, we use define to wrap logic that will be re-used to the other places of application. And, we use require to load dependency onto the page. 

Shim Configuration

Shim configuration is used in RequireJS to configure or use scripts that are not AMD compatible.

It is very useful for libraries that exports a global variable as below:
  1. requirejs.config({  
  2.   shim: {  
  3.     'backbone': {  
  4.         deps: ['underscore''jquery'],  
  5.         exports: 'Backbone'  
  6.     }  
  7.   }  
  8. });  
deps: An array of dependencies to load. Useful when require is defined as a config object before require.js is loaded, and you want to specify dependencies to load as soon as require() is defined.
 
It is also useful for declaring dependencies like below:
  1. require.config({  
  2.   shim: {  
  3.     'jquery.ui.widget': ['jquery'],  
  4.       
  5.     'jquery.selectBoxIt': ['jquery.ui.widget']  
  6.   }  
  7. });  

Config 

RequireJS allows to set application-level configuration. It should be set before the define or require of any module.
 
Configuration options:
  1. baseUrl: It should be the beginning file path that is being used for all of the file look ups.
  2. paths: It allows us to map module IDs to alias names.
  3. shim: It allows us to make third-party libraries AMD compatible. 
Example: 
  1. 'use strict';  
  2.   
  3. requirejs.config({  
  4.   
  5.     baseUrl:'js',  
  6.   
  7.     paths:{  
  8.   
  9.         'text''../lib/require/text',   
  10.         'jquery''../lib/jquery/jquery',  
  11.         'jquery-ui''../lib/jquery/jquery-ui-1.10.2.min',  
  12.         'angular''../lib/angular/angular',  
  13.         'library''../lib'  
  14.     },  
  15.       
  16.     shim:{  
  17.         'angular':{  
  18.             deps:['jquery'],  
  19.             exports:'angular'  
  20.         },  
  21.         'jquery-ui': {  
  22.             deps: ['jquery']   
  23.         },  
  24.         'app':{  
  25.             deps:['angular']  
  26.         },  
  27.         'routes':{  
  28.             deps:['angular']  
  29.         }  
  30.     }  
  31. });  
  32.   
  33. requirejs( [  
  34.         'text',   
  35.         'jquery',   
  36.         'angular',   
  37.         'jquery-ui',  
  38.         'app',   
  39.         'routes'   
  40. ],  
  41.   
  42.     function (text, $, angular) {  
  43.   
  44.         $(document).ready(function () {  
  45.             angular.bootstrap(document, ['myApp']);  
  46.         });  
  47.           
  48.     }  
  49. );  

Conclusion

Require.js is a very powerful library for managing dependencies. Later, I will add one project implemented with Require.js.