Skip to content

AMD Modules (RequireJS)

Tim Branyen edited this page Oct 13, 2013 · 1 revision

The RequireJS configuration is consumed whenever you hit refresh while developing in the browser. It is also consumed whenever you run grunt to optimize your project. This is important, as it helps you seamlessly author modules and optimize them.

This file path for this config is: app/config.js.

It is required by app/main.js and is loaded before app/app.js. Multiple files are necessary to separate the configuration from application initialization. For instance, in the RequireJS documentation on loading JavaScript, shows combining the configuration and the application together. In practice this is a bad idea. The implication becomes that you must start the application in order to configure your module loader. This is a hindrance when trying to test modules in isolation.

Adding paths.

Looking at the configuration file there are mappings between module names and locations in the vendor directory:

"jquery": "../vendor/bower/jquery/jquery"

The above code snippet points to the top level vendor directory, into the installed bower modules, and finds the jquery.js file. The .js extension must be omitted, because RequireJS assumes you author JavaScript. The only exception to this, is if you use a URL instead of a file path. Those must end with the proper extension.

Shimming.

The concept of a shim configuration came out of the need for easily consuming third party modules that did not export an AMD interface.

At a high level it allows you to load any arbitrary JavaScript, but configure Require to load any dependencies first and then map the window.libraryName object to export.

The configuration looks like this:

shim: {
  "MODULE_NAME": {
    deps: <ARRAY OF MODULE NAMES>
    exports: <NAME OF OBJECT PROPERTY ON WINDOW>
  }
}

An example is provided in the configuration to consume the Backbone library. You'll notice that neither the LoDash underscore build or jQuery need to be shimmed. This is because they export to AMD already.