requirejs使用

 

实现模块化、按需加载。

一.配置参数

1.baseUrl以一个相对于baseUrl的地址来加载所有的代码。

  data-main,使用它来启动脚本加载过程,而baseUrl一般设置到与该属性相一致的目录。也可以通过config来配置。如下:

如果没有显式指定config及data-main,则默认的baseUrl为包含RequireJS的那个HTML页面的所属目录。

<script data-main="scripts/main.js" src="scripts/require.js"></script>

2.定义模块:

defined:

define(["my/cart", "my/inventory"],
    function(cart, inventory) {
        //return a function to define "foo/title".
        //It gets or sets the window title.
        return function(title) {
            return title ? (window.title = title) :
                   inventory.storeName + ' ' + cart.name;
        }
    }
)

3.require  引入

requirejs(['jquery', 'canvas', 'app/sub'],
function   ($,        canvas,   sub) {
    //jQuery, canvas and the app/sub module are all
    //loaded and can be used here now.
});
//入參 三个。
context.require(deps, callback, errback)

4.paths 

path映射那些不直接放置于baseUrl下的模块名。设置path时起始位置是相对于baseUrl的,除非该path设置以"/"开头或含有URL协议(如http:)。

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

如果shim对象的value值里的对象有init会先执行并返回 赋值 给 exportsFn,否则 有export会返回export,否则返回公共的export。赋值 给 exportsFn。

处理函数如下:

//处理shim配置的exports
            makeShimExports: function (value) {
                function fn() {
                    var ret;
                    if (value.init) {
                        ret = value.init.apply(global, arguments);
                    }
                    return ret || (value.exports && getGlobal(value.exports));
                }
                return fn;
            },

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

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

6.map: 对于给定的模块前缀,使用一个不同的模块ID来加载该模块。

另外在map中支持“*”,意思是“对于所有的模块加载,使用本map配置”。如果还有更细化的map配置,会优先于“*”配置。

requirejs.config({
    map: {
        '*': {
            'foo': 'foo1.2'
        },
        'some/oldmodule': {
            'foo': 'foo1.0'
        }
    }
});

意思是除了“some/oldmodule”外的所有模块,当要用“foo”时,使用“foo1.2”来替代。对于“some/oldmodule”自己,则使用“foo1.0”。

 
原文地址:https://www.cnblogs.com/rainbow661314/p/5664707.html