官方示例:
http://www.requirejs.org/jqueryui-amd/example/webapp/app.html
/** * Ask for 'require', 'jquery' and 'jqueryui/tabs' as dependencies. * * 'require' is asked for as best practice, since it used inside the * require callback to dynamically load the datepicker. Since 'require' * is a module (provided by RequireJS), it is passed as the first argument * to the require callback. "req" is used as the function argument name * so the RequireJS optimizer will not pick up the dynamic load of * the 'jqueryui/datepicker', 'jqueryui/datepicker-fr' modules and * include them in the optimized build for main.js (see app.build.js * for more information on the optimized main.js build profile.) * * The require-jquery.js file registers jQuery as a module, * so this require callback will receive it as the second function * argument, since 'jquery' is the second dependency in the * dependency array. * * 'jquery/ui/tabs' does not export a module * value (it just augments jQuery), so it will not have a value for it * passed to the require callback. No need to assign a function argument * for it. */ require({ //Set config for finding 'jqueryui'. The path is relative //to the location of require-jquery.js. paths: { jqueryui: 'jqueryui-1.8.13/jqueryui' } }, ['require', 'jquery', 'jqueryui/tabs'], function (req, $) { //Wait for dom ready before setting up widgets. $(function () { //Make the tabs. $('#tabs') .tabs({ load: function (event, ui) { //If the second tab is clicked, dynamically load //the datepicker. if (ui.index === 1) { //Load the datepicker in French, on demand. req(['jqueryui/datepicker', 'jqueryui/datepicker-fr'], function () { $('#datepicker').datepicker(); } ); } } }) //Make the tabs visible now that the widget has been instantiated. .removeClass('invisible'); }); });
网上帖子:
理论上,require.js加载的模块,必须是按照AMD规范、用define()函数定义的模块。但是实际上,虽然已经有一部分流行的函数库(比如jQuery)符合AMD规范,更多的库并不符合。那么,require.js是否能够加载非规范的模块呢?
回答是可以的。
这样的模块在用require()加载之前,要先用require.config()方法,定义它们的一些特征。
举例来说,underscore和backbone这两个库,都没有采用AMD规范编写。如果要加载它们的话,必须先定义它们的特征。
require.config({ shim: { ‘underscore’:{ exports: ‘_’ }, ‘backbone’: { deps: [‘underscore’, ‘jquery’], exports: ‘Backbone’ } } });
require.config()接受一个配置对象,这个对象除了有前面说过的paths属性之外,还有一个shim属性,专门用来配置不兼容的模块。具体来说,每个模块要定义(1)exports值(输出的变量名),表明这个模块外部调用时的名称;(2)deps数组,表明该模块的依赖性。
比如,jQuery的插件可以这样定义:
shim: { 'jquery.scroll': { deps: ['jquery'], exports: 'jQuery.fn.scroll' } }