RequireJS Basics

May 22, 2017

Requirejs Official Documentation

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:

|     |--main.js
|     |--app.js
|     |--lib/
|     	  |--jquery-3.2.1.js
|     	  |--require.js

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


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 loads the requirejs configuration and our own modules. The main.js file loo

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

    baseUrl: 'scripts',
    paths: {
        //The libraries we use:
        jquery: [
        //Try loading from CDN first:
        //If it can't load from the CDN, it'll load the local version below:

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


app.js is a module we’ve written. It’s kind of like the 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