Thursday 30 April 2015


RequireJS Getting Started

RequireJS is probably the most wide spread implementation of the AMD API nowadays. If its documentation is rather thick, it still may leave you with the feeling that it lacks a simple example that would help you get started. The goal of this tutorial is to show you the fundamentals in the easiest possible way in order to be able to experiment with Require, through a minimalist example.

A simple example

 

index.html

 














<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Basic example of requireJS integration</title>
</head>
<body>
<div id="container">
    <p>Check console and js files</p>
</div>
<script data-main="js/main" src="js/vendor/require.js"></script>
</body>
</html>

We begin with a basic structure.
The script tag that calls require.js includes a “data-main” attribute pointing to the js/main.js file, without its extenstion (we can however keep it if we want).
The location of the main.js file is important, as it will be the root from which the modules will be looked for.

js/main.js

 








// Load modules and use them
require(['module1', 'path/to/module2'], function(module1ref, module2ref){
    // do something with the loaded modules
    var module1 = new module1ref(),
          module2 = new module2ref();
    console.log(module1.getName() === module2.getModule1Name()); // true
});

The require() function takes two arguments: an array of dependencies, and a callback function to execute once all the dependencies are loaded.
This callback function takes for parameters the specified dependencies, in their order of apparition in the array.
Here, we load module1 and module2, and we pass them to the callback function under the name “module1ref” and “module2ref” respectively.
The parameters passed in the dependency array are the names of the JavaScript files containing the modules, without their extension. They can contain a path, which will be relative to the location of the main.js file.

js/module1.js

 












define([], function () {
    var returnedModule = function () {
        var _name = 'module1 name';
        this.getName = function () {
            return _name;
        }
    };
    return returnedModule;
});

To create a module, we use the define() function provided by RequireJS.
This function, as in the case of the require() function, can specify some dependencies.
It has to return something, which will be forwarded to the callback function.
Here, we return a function that exposes a getName() method allowing us to to get the” private variable “_name.

js/path/to/module2.js

 












define(['module1'], function (module1ref) {
    var module1 = new module1ref();
    var returnedModule = function () {
        this.getModule1Name = function () {
            return module1.getName();
        }
    };
  
    return returnedModule;
  
});

For this second module, we have declared a dependency on the module1, which becomes available under the name module1ref in the callback function.
This module returns a function too, which exposes the getModule1Name() method. We can thus see how we can make use of a dependecy within a module.
Of course, you have total freedom on what you do with those dependencies within a module, and I’m sure you will find some way more interesting usages than the one in this exemple! ;)

Loading dependencies that aren’t modules

You will probably soon enough need to load third party libraries that aren’t defined as Require modules, like for example jQuery or underscore.js.
For this, James Burke (the author of RequireJS) provides a “shim” system to us.

js/main.js

 
























require.config({
    paths: {
        'jQuery': 'vendor/jquery-1.9.0.min',
        'underscore': 'vendor/underscore-1.9.min'
    },
    shim: {
        'jQuery': {
            exports: '$'
        },
        'underscore': {
            exports: '_'
        }
    }
});
require(['module1', 'path/to/module2', 'jQuery'], function (module1ref, module2ref, $) {
    // do something with the loaded modules
    var module1 = new module1ref(),
          module2 = new module2ref();
    console.log(module1.getName() === module2.getModule1Name()); // true
    console.log('jQuery version:', $.fn.jquery); // 1.9.0
});

In order to use jQuery as a dependency, we must tell RequireJS two things: the path where to find the JavaScript file, and the global variable we wish to get hold of.
To do so, we have to provide a configuration object to the config() method of the “require” (or “requirejs”, both are identical) global object.
This configuration object defines under its “paths” key the names of the virtual modules, as keys for which the value represents the file we want to load.
Under the “shim” key of the configuration object, we use those keys to point to the global variable defined by the library we want to get hold of.
It’s this variable that will be returned when we call the module thus defined.
Here again, the “paths” declared are relative to the location of the main.js file and don’t include their .js extension.

No comments:

Post a Comment