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

未来可能将该部分代码置入require/目录下作为一个可选模块,这样你可以在你的宿主环境中使用它来获得正确的加载顺序。

§ 3.配置选配

当在顶层HTML页面(或不作为一个模块定义的顶层脚本文件)中,可将配置作为首项放入:

<script src="scripts/require.js"></script>
<script>
 require.config({
  baseUrl: "/another/path",
  paths: {
    "some": "some/v1.0"
  },
  waitSeconds: 15
 });
 require( ["some/module", "my/module", "a.js", "b.js"],
  function(someModule,  myModule) {
    //This function will be called when all the dependencies
    //listed above are loaded. Note that this function could
    //be called before the page is loaded.
    //This callback is optional.
  }
 );
</script>
<script>
  var require = {
    deps: ["some/module1", "my/module2", "a.js", "b.js"],
    callback: function(module1, module2) {
      //This function will be called when all the dependencies
      //listed above in deps are loaded. Note that this
      //function could be called before the page is loaded.
      //This callback is optional.
    }
  };
</script>
<script src="scripts/require.js"></script>

或者,你将配置作为全局变量"require"在require.js加载之前进行定义,它会被自动应用。下面的示例定义的依赖会在require.js一旦定义了require()之后即被加载:

requirejs.config({
  bundles: {
    'primary': ['main', 'util', 'text', 'text!template.html'],
    'secondary': ['text!secondary.html']
  }
});
require(['util', 'text'], function(util, text) {
  //The script for module ID 'primary' was loaded,
  //and that script included the define()'d
  //modules for 'util' and 'text'
});

注意: 最好使用 var require = {} 的形式而不是 window.require = {}的形式。后者在IE中运行不正常。

支持的配置项:

baseUrl :所有模块的查找根路径。所以上面的示例中,"my/module"的标签src值是"/another/path/my/module.js"。当加载纯.js文件(依赖字串以/开头,或者以.js结尾,或者含有协议),不会使用baseUrl。因此a.js及b.js都在包含上述代码段的HTML页面的同目录下加载。

如未显式设置baseUrl,则默认值是加载require.js的HTML所处的位置。如果用了data-main属性,则该路径就变成baseUrl。

paths :path映射那些不直接放置于baseUrl下的模块名。设置path时起始位置是相对于baseUrl的,除非该path设置以"/"开头或含有URL协议(如http:)。在上述的配置下,"some/module"的script标签src值是"/another/path/some/v1.0/module.js"。

用于模块名的path不应含有.js后缀,因为一个path有可能映射到一个目录。路径解析机制会自动在映射模块名到path时添加上.js后缀。在文本模版之类的场景中使用require.toUrl()时它也会添加合适的后缀。

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

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