Dojo FAQ: How does passing a configuration object to require work?

By on January 22, 2014 10:04 am

DojoFAQ
Anyone who has developed applications with Dojo’s AMD loader will have used the require function to asynchronously load modules. Must of the time, a require call takes the form require(['path1', 'path2'], function(module1, module2) { ... });. However, require will also accept an optional parameter before the path list, a configuration object. This object configures the Dojo loader, much like the global dojoConfig property or data-dojo-config attribute.

Configuration objects allow the Dojo loader to be lazily configured rather than requiring that all configuration parameters be set before dojo.js is loaded. In the example below, we provide a configuration object that maps the module identifier fragment “demo” to the path location.href + "demo".

require({
	paths: {
		demo: location.pathname + "demo"
	}
}, ["demo/myModule"], function (myModule) {
	console.log(myModule.someProperty);
});

Configuration changes made with require are persistent (until/unless changed by another call to require). If we were to require a module at a later time whose module ID started with “demo”, the loader would look in the path set in the require call above.

The require function can even be used just to configure the loader. In the following example, we first configure the loader by passing a configuration object to require, then make use of the property in a later require call:

require({
	paths: {
		demo: location.pathname + "demo"
	}
});

require(["demo/myModule"], function (myModule) {
	console.log(myModule.success);
});

Configuration objects can be used to change many, but not all, properties of the loader. For example, the async loader flag must still be set in a global property. Another point to keep in mind is that configuration object properties are shallow copied into the loader’s configuration. In the example above, the value of the paths property will replace the existing value of paths rather than simply adding a value for the demo property. The loader’s micro-event API can be used to mix values into existing configuration properties. Listeners that are registered to receive “config” events from the loader will be called whenever the configuration changes. These listeners will be passed the loader’s configuration object, which they can update as needed.

As you can see, configuration objects allow application-specific options to be encapsulated, allowing for a cleaner and easier-to-read configuration of the Dojo loader.