« Back to Index

There are a couple of different ways to require a module using RequireJS

View original Gist on GitHub

different ways to require module.md

require(['module-cjs-sugared-form', 'standard', 'async-callback'], function(a, b, c) {
    console.log('main page (a):', a);
    console.log('main page (b):', b, b.a, b.b);
    console.log('main page (c):', c);
});

CJS Sugared Version…

define(function(require) {
    var a = require('a');
    console.log('cjs:', a);
    return a;
});

The above converts internally to the standard AMD format…

define(['require', 'a'], function(require) {
    var a = require('a'); // sync call, but module already loaded
    console.log(a);
});

…this conversion happens whenever no dependency list is specified.

RequireJS will see no dependencies specified and then start scanning for require('some-string') instead and do the conversion using any it finds as dependencies.

So require('a') will returned the already loaded dependency ‘a’ as a cached module.

The following would cause an error because the module hasn’t been loaded…

define(['a'], function(a) {
    var b = require('b'); // would cause an error -> not loaded yet for context
    return {
        a: a,
        b: b
    };
});

The following is an asynchronous loading mechanism…

define(['require', 'a'], function(require, a) {
    var b = require(['b'], function(b) {
        console.log('b callback', b);
    });

    return {
        a: a,
        b: b
    };
});