require
As in AMD loaders, require
can be used to define an anonymous action to be invoked when all dependencies are resolved, or to retrieve an already-resolved resource by name.
resource.js operates within one or more
Context
s. The globally exported variableresource
is also a reference to the current default context. The global functionrequire
is an alias for therequire
method on the current default context. Thusrequire
is an alias forwindow.resource.require
, andrequire
can also be called on anyContext
instance.
require(resourceID:string):any
require(dependency:string, action:Function):void
require(dependencies:string[], action:Function):void
The whole point of defining your resources is to be able to use them without worrying about the load order of dependencies. We do this with require
:
// An anonymous function to be invoke when all dependencies are resolved
require(['jquery', 'app-user-form'], function($, UserForm) {
new UserForm($('#user-form'));
});
// If there is only on dependency, it can be provided as a bare string
require('all-the-things', function(things) {
things.doStuff();
});
At any point in code, you can retrieve a resolved resource by calling require
with a single string argument. This does not guarantee that the resource has been defined or resolved, but inside a define
or require
call, this can be used for a CommonJS-like syntax, so you don't have to meticulously order your dependency names and injected parameters:
define(
'app-user-form',
// You still have to declare your dependencies
['jquery', 'bootstrap', 'app-constants', 'app-form-base', 'jquery-date-picker'],
function() {
// But you can retrieve them by name with require:
let $ = require('jquery');
let FormBase = require('app-form-base');
...
});
This also makes it easy to define bundle resources, while still retrieving individual resources as needed:
define('all-the-basics', ['jquery', 'bootstrap', 'app-root', 'app-constants', 'app-form-base', 'jquery-date-picker'], function() {
return require('app-root');
});
define('app-user-form', ['all-the-basics'], function() {
let $ = require('jquery');
let FormBase = require('app-form-base');
...
});