Skip to content

require

Joshua Honig edited this page Nov 13, 2017 · 6 revisions

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 Contexts. The globally exported variable resource is also a reference to the current default context. The global function require is an alias for the require method on the current default context. Thus require is an alias for window.resource.require, and require can also be called on any Context instance.

Syntax

require(resourceID:string):any
require(dependency:string, action:Function):void
require(dependencies:string[], action:Function):void 

Schedule an anonymous function to be invoked when all dependencies are resolved

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();
});

Retrieve an already resolved resource

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');
    ...
});