Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / AngularJs

Integrating requirejs in your angularjs application

3.33/5 (3 votes)
5 Jan 2016CPOL3 min read 22.2K  
Using requirejs to load modules asynchronously in angularjs application.

Introduction

This article details how to use requirejs library in your AngularJs application.

Background

RequireJs website defines RequireJS as a JavaScript file and module loader. 
Using a modular script loader like RequireJS will improve the speed and quality of your code.The files will be loaded asynchrounously when needed, rather than loading all at once.

If you are not using requireJs in your application you must be loading all of your angularjs code files using script tags. We will see in this article how to use requirejs to lazy load modules

Prerequisites 

I would be using bower to get my dependencies. For those who don't know bower, it's a node utility to download all of you front end dependencies using commands.
All of your dependencies will be saved in bower_components folder by default. However you have liberty to change this folder.

To install bower you need to open up command prompt and say "npm install -g bower". -g flag is to install bower globally so that we can use bower across all projects. You can omit -g flag if you wish to. 

We have two dependencies for our demo project
1. AngularJs
2. RequireJs

Let's start

Create a folder on your hard drive to start our project. For instance I would create on my D: drive namely RequireJsDemo.

To install them one by one run following two commands by navigating to the above said folder in D drive.(or whatever drive your project is in).
i. bower install angularjs
ii. bower install requirejs

Once everything is installed fine, you should have bower_components directory created and has two folders inside it namely angular and requirejs.

Step1: Add config file for requirejs (main.js)

require.config({
    paths: {
        angular: 'bower_components/angular/angular'
    },
    shim: {
        "angular": {
            exports: "angular"
        }
    }
})

main.js has configuration code for requirejs in which we are registering and exporting angularjs. 

Next create a folder by the name "src" and two empty javascript files for now, as shown below.

RequireJsDemo

       ---bower_components

       --src

             --controller.js

             --module.js

 

Step2: Create controller

Paste the below code in controller.js file

define([], function () {
    var myController = function ($scope) {
        $scope.message = "RequireJs Integrated successfully";
    };

    myController.$inject = ['$scope'];

    return myController;
});

We create a require module using define function. It's a global function and takes two arguments. 
First one is the array of dependent files while the second is a function. Here our controller file doesn't have any dependencies so I specified an empty array as the first parameter.
In the second function argument i wrapped my controller. Controllers are nothing but javascript functions so i am returning a function from this module.
I am using $inject service to inject my dependencies, though it's not mandatory but to make your module min-safe it's needed.

Same way I will write code inside my modulejs where i would be creating an angularjs module.

define(['angular', 'src/controller'], function (angular,controller) {
    angular.module('app',[])
        .controller('myController', controller);
});

In the above code snippet I am defining my module using define global function of requirejs. This time define function has two dependencies one is angular and the other one is our controller file. (Note that i am not using .js extension while specifying dependencies). In the next line I am creating a module and attaching controller to it.

Step3: Add index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RequireJs Demo</title>

    <script src="bower_components/requirejs/require.js" data-main="main.js"></script>
</head>
<body ng-controller="myController">
{{message}}
</body>
</html>
 
Note that i am using only one script tag that is to reference requirejs. Requirejs library will take care of loading angular itself and our controller.js and module.js files.

Step4: Bootstrap application: 

I can not use ng-app to bootstrap my application because requirejs loads modules asynchronously. Luckily there is a solution to this problem. I can manually bootstrap my app as shown below.

require(['angular', 'src/module'],
    function () {
        angular.bootstrap(document, ['app']);
    }
);

my main.js file would be as shown below after adding bootstrap code.

require.config({
    paths: {
        angular: 'bower_components/angular/angular'
    },
    shim: {
        "angular": {
            exports: "angular"
        }
    }
});

require(['angular', 'src/module'],
    function () {
        angular.bootstrap(document, ['app']);
    }
);

That's all, go ahead and run the application. You should see "RequireJs Integrated successfully" message on your web page.

Points of Interest

If you are working with large application where you have tens of script files, you need to add them in your index.html file using script tags. Moreover they need to be added in proper order. Requirejs makes things easy by lazy loading modules. You don't need to bear the pain of ordering your script tags.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)