详解RequireJs官方使用教程(7)

在浏览器中运行时,可指定路径的备选(fallbacks),以实现诸如首先指定了从CDN中加载,一旦CDN加载失败则从本地位置中加载这类的机制。

shim: 为那些没有使用define()来声明依赖关系、设置模块的"浏览器全局变量注入"型脚本做依赖和导出配置。

下面有个示例,它需要 RequireJS 2.1.0+,并且假定backbone.js、underscore.js 、jquery.js都装于baseUrl目录下。如果没有,则你可能需要为它们设置paths config:

requirejs.config({
  //Remember: only use shim config for non-AMD scripts,scripts that do not already call define().
  //The shimconfig will not work correctly if used on AMD scripts,
  //in particular, the exports and init config will notbe triggered, and the deps config will be confusingfor those cases.
  shim: {
    'backbone': {
      //These script dependencies should be loaded before loadingbackbone.js|译|在加载backbone.js之前应先加载它的依赖函数underscore.js和jquery.js
      deps: ['underscore', 'jquery'],
      //Once loaded, use the global 'Backbone' as themodule value.|译|加载完毕后该模块使用的引用名
      exports: 'Backbone'
    },
    'underscore': {
      exports: '_'
    },
    'foo': {
      deps: ['bar'],
      exports: 'Foo',
      init: function (bar) {
        //Using a function allows you to call noConflict forlibraries that support it, and do other cleanup.
        //However, plugins for those libraries may still want a global.
        //"this" for the function will be the global object.
        //The dependencies will be passed in as function arguments.
        //If this function returns a value,then that value is used as the module export valueinstead of the object found via the 'exports' string.
        //Note: jQuery registers as an AMD module via define(),so this will not work for jQuery.
        //See notes sectionbelow for an approach for jQuery.
        return this.Foo.noConflict();
      }
    }
  }
});
//Then, later in a separate file, call it 'MyModel.js', a module is defined,specifting 'backbone' as a dependency.
//RequireJS will use the shim config to properly load 'backbone' and give a local reference to this module.
//The global Backbone will still exist on the page too.
define(['backbone'], function (Backbone) {
 return Backbone.Model.extend({});
});

 RequireJS 2.0.*中,shim配置中的"exports"属性可以是一个函数而不是字串。这种情况下它就起到上述示例中的"init"属性的功能。 RequireJS 2.1.0+中加入了"init"承接库加载后的初始工作,以使exports作为字串值被enforceDefine所使用。

那些仅作为jQuery或Backbone的插件存在而不导出任何模块变量的"模块"们,shim配置可简单设置为依赖数组:

requirejs.config({
  shim: {
    'jquery.colorize': ['jquery'],
    'jquery.scroll': ['jquery'],
    'backbone.layoutmanager': ['backbone']
  }
});
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1271.html