2015-04-03 49 views
-1

我无法理解requirejs.config()函数。requirejs.config()做什么?

requirejs.config({ 
    paths: { 
     'text': '../lib/require/text', 
     'durandal':'../lib/durandal/js', 
     'plugins' : '../lib/durandal/js/plugins', 
     'transitions' : '../lib/durandal/js/transitions', 
     'knockout': '../lib/knockout/knockout-3.1.0', 
     'bootstrap': '../lib/bootstrap/js/bootstrap', 
     'jquery': '../lib/jquery/jquery-1.9.1' 
    }, 
    shim: { 
     'bootstrap': { 
      deps: ['jquery'], 
      exports: 'jQuery' 
     } 
    } 
}); 

该功能做什么?请不要将我引导至文档,因为我已经阅读并仍然觉得很困惑。我需要一个关于这个函数做什么的简单解释。

这些脚本是异步加载的吗?

回答

1

它为脚本路径创建别名ant告诉如何在加载时解释bootstrap(非AMD脚本)。没有任何装载。您有权要求:

// we load two dependencies here 
// `knockout` and `bootstrap` are expanded to values in config 
// .js added to values 
// callback function called when all dependencies are loaded 
require(['knockout', 'bootstap'], function(Knockout, $) { 
    // jQuery is passed to this function as a second parameter 
    // as defined in shim config exports 
}); 
+0

你的意思是说这里唯一的非AMD脚本是bootstrap吗? – DesirePRG 2015-04-03 19:54:00

+0

并不是一件坏事。但是shim config用于“amdify”脚本。您可以安全地跳过它并使用全局实例。 – 2015-04-03 20:00:00

0

路径就像声明/定义。因此,例如,

jquery: '../bower_components/jquery/dist/jquery', 

您可以稍后加载此库,如下所示。

define([ 
    'jquery' 
], function (jquery) { 
    //initialize or do something with jquery 
} 

您不必指定库的绝对路径。

垫片中,您将定义依赖关系。因此,例如,

paths: { 
    template: '../templates', 
    text: '../bower_components/requirejs-text/text', 
    jquery: '../bower_components/jquery/dist/jquery', 
    backbone: '../bower_components/backbone/backbone', 
    underscore: '../bower_components/underscore/underscore', 
    Router: 'routes/router' 
}, 
shim: { 
    'backbone': ['underscore', 'jquery'], 
    'App': ['backbone'] 
} 

这里骨干取决于强调的jQuery。所以这两个库将在骨干网开始加载之前加载。同样应用程序将加载骨干网后加载。

如果您熟悉骨干和快递,您可能会发现这个回购有用。

https://github.com/sohel-rana/backbone-express-boilerplate

+0

所以如果有任何js依赖于另一个js,我必须将它们放入垫片中? – DesirePRG 2015-04-03 20:05:31

+0

是的,你必须在垫片中定义它们。因为JS会异步加载。但通常你会有依赖于其他库的lib。例如,一个jquery插件需要先加载jquery。所以你必须添加jQuery作为该插件的依赖。 – Sohel 2015-04-03 20:21:36