You are looking at documentation for an older release. Not what you want? See the current release documentation.
In this section you learn uses of shim configuration. Basically shim configuration is something you add in requirejs.config() when you need:
Synchronous dependencies loading.
Non-AMD libraries.
RequireJS documentation introduces shim configuration in one example. Here it breaks into three simpler samples: deps, exports and init.
Synchronous dependencies loading
Remember "A" in AMD stands for "Asynchronous"? It aims at optimizing performance. However when you need two libraries and one of them depends on the other, you use shim deps configuration to load them in order.
require.config({ baseUrl: "js", paths: { jquery: "jquery-1.7.1", util: "util" }, shim: { // util depends on jquery. // util is non-AMD. "util": { deps: ["jquery"] } } });
The idea is as simple as you see it. Only one thing that needs explanation: "util" in this example is non-AMD, because shim will not work on AMD libraries. If "util" complies AMD, it should declare its dependencies using this form of define():
define(["jquery"], function(jquery){...});
Non-AMD with exports
With the following shim configuration, the util
module will hold a local (in require scope) reference to the global
count
variable.
shim: { "util": { exports: "count" } }
To see it in action, let's modify the previous example to make "util" a non-AMD module.
Edit util.js
to be a closure which declares a global variable:
(function (){ var counter = 0; // count is global count = function(){ return ++counter; }; })();
In my.js
, "count" is exported and referenced by the name "util", in the scope of "require":
require.config({ baseUrl: "js", paths: { jquery: "jquery-1.7.1", util: "util" }, shim: { "util": { exports: "count" } } }); function myClick(){ require(["util", "jquery"], function(util, $){ $("#result").text(util); }); }
As you may ask, the global "count" is still available (after require() execution finishes).
Non-AMD with init
The init function can be used to do some tweaks with non-AMD library, for example to remove a global variable.
The simplest use of init function can be considered as an alternative of exports. In the below example, you return "count" in init function, it is equivalent to exporting "count".
require.config({ baseUrl: "js", paths: { jquery: "jquery-1.7.1", util: "util" }, shim: { "util": { //exports: "count" init: function() { return count; } } } });
If you need to use dependencies in init function, write it with parameters as below:
require.config({ baseUrl: "js", paths: { jquery: "jquery-1.7.1", util: "util" }, shim: { "util": { deps: ["jquery"], init: function (jquery) { // } } } });
References
This section explains uses of shim configuration and how Non-AMD modules can be used with RequireJS. Please do not miss the important notes in RequireJS documentation: