This example shows one way to load jQuery and jQuery plugins with require.js. jQuery itself registers as an AMD module and can easily be loaded. Most plugins, however, does not register as AMD modules, and therefore, require.js doesn't know that the plugins need jQuery to be loaded.
The most important part is the app.js file, which specifies the shim configuration for the plugins.
###Project structure
-
tools/
- build.js
- r.js
-
www/
- app.html
- js/
- app.js
- lib/
- jquery.js
- jquery.alpha.js
- jquery.beta.js
- require.js
- app/
- main.js
###How it's set up The main file of this setup is www/js/app.js. It is loaded from app.html by this line:
<script data-main="js/app" src="js/lib/require.js"></script>
App.js is mainly about configuration. The shim configuration specifies jQuery as a dependency for jQuery.alpha and jQUery.beta. Finally, our main code is loaded at the bottom of the file:
requirejs.config({
"baseUrl": "js/lib",
"paths": {
"app": "../app"
},
"shim": {
"jquery.alpha": ["jquery"],
"jquery.beta": ["jquery"]
}
});
// Load the main app module to start the app
requirejs(["app/main"]);
App/main.js is where the app logic is:
define(["jquery", "jquery.alpha", "jquery.beta"], function($) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
$('body').alpha().beta();
});
});
###How to see it in action
Just serve up the www/ folder using any web server you'd like. If you have python installed, an easy way is to navigate into the www/ directory and type python -m SimpleHTTPServer
###How to optimize ut using r.js To use the optimizer, you need node.js or Java 6 installed. These instructions assume Node is being used. See the Optimization page for more information.
r.js and a build configuration is included in the tools/ folder. To build, navigate to tools/ and type node r.js -o build.js
. You will find the built product in the www-build folder. If you serve that directory instead, you can see in the network panel of the web developer tools that the files aren't loaded separately any more.