RequireJS Basics

May 22, 2017

Requirejs Official Documentation

Context Requirejs is used to asynchronously load javascript modules. I needed to use this for a game project for a client, and they wantedit in requirejs format. My javascript is weak at this point, so this was an excercise, not only in requirejs but in javascript itself.

For basic usage with JQuery, you need the following files:

|--scripts/
|     |--main.js
|     |--app.js
|     |--lib/
|     	  |--jquery-3.2.1.js
|     	  |--require.js
|--index.html

Download RequireJS and JQuery. These go in your lib folder.

index.html

The index.html file should have the script tag below in the head tag. This allows require.js to call the entry point of all your javascript, specified in the data-main attribute - main.js.

<script data-main="scripts/main" src="scripts/lib/require.js"></script>

main.js

main.js loads the requirejs configuration and our own modules. The main.js file loo

//This is the first js file to be loaded.

//Configuration
requirejs.config({
    baseUrl: 'scripts',
    paths: {
        //The libraries we use:
        jquery: [
        //Try loading from CDN first:
        '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min',
        //If it can't load from the CDN, it'll load the local version below:
        'lib/jquery-3.2.1'
        ]
    }
});


//Main
require(['jquery', 'app'], function($, app){
    $('#testing').html('this is the main module');
    app.init();
});

app.js

app.js is a module we’ve written. It’s kind of like the init.py in a python package. For a smaller app, it can contain all the logic. For larger apps it’s where you can weave together all the rest of the modules. RequireJS way of doing things also seems to encourage one module = one class. The modules should contain all it’s code in a ‘define’ block, with dependencies passed as a list.

define(['jquery'], function($) {
    
    // all code here

});

I'll tell you when I post stuff.

Subscribe to get my latest posts by email.