我正在实现将在第三方网站上使用的面向AMD模块的JS框架。
使用此行,框架用户将配置必要的模块
<script data-main="/main.js" src="/require.js"></script>
问题是data-main
参考是异步加载的,因此,根据main.js
加载的模块,除非我确定它完成的加载。
我是Requirejs的新手
如何解决这个非常简单的问题?
编辑解释我的观点的一个例子
main.js
requirejs.config({
paths: {
jquery: '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min',
}
});
主JS参考 额外代码
<script data-main="/main.js" src="/require.js"></script>
<script>
require(['jquery'], function($) {
// since main.js is not loaded yet, it will assume that there is a jquery.js
// file on the same folder that this file
console.log('myModule was also loaded and can use jQuery');
});
</script>
如果您想依靠其他库,并且专门针对需要管道中的库,那么您需要做的就是声明某些依赖项
define(
'myModule', // module name
['foo'], // module dependencies
function(foo){ // module construction
var myModule = {};
.... code to set up the module ....
return myModule;
});
和需要会照顾好事。这将在您的模块上注册您的模块,并且在所有依赖项都可用之前不会尝试构建模块。此功能在这里讨论。
更新示例
requient js旨在使用有或没有预构建配置的情况下工作。paths
属性config对象的属性仅提供有关如何尝试查找尚未注册的库的信息。但是,不管模块的注册方式/何处,注册和依赖分辨率都通过要求处理。请参阅此JSFIDDLE,以获取您如何注册并使用依赖项的工作示例。
更新2关于config
由于requirejs会不同步加载所有内容,因此您是正确的,您的代码示例将行不通。但是,您对它的"假定"工作方式做出了错误的假设。您有一个不正确的示例,说明了库客户端的要求的外观。如果其他人正在使用requirejs构建应用程序,并且他们想使用您的库,则应在require.config
中声明您库的路径:
require.config({
paths: {
// this tells require how to load jQuery (a library maintained neither by you nor your clients).
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min',
// this tells require how to load myModule (the library you are building for your clients).
'myModule': '//example.com/js/my-module.min',
// this tells require how to load foo (a library built and hosted by your clients).
'foo': 'scripts/foo'
}
});
另一方面,如果您的客户端无法更新他们的要求配置以将您的库包含在声明中,那么您就不幸了。您所能做的就是将所有依赖项捆绑在分发文件中,然后声明不依赖性:
define(
'myModule',
[], // can't declare any dependencies
function() {
// these dependencies are inside of the definition function to keep the global namespace clean
// since we need jQuery, we have to inline it:
var jQuery = ....
// same goes for d3.js
var d3 = ....
// now we can set up the module itself
var myModule = {};
.... code to set up the module ....
return myModule;
}
);
显然,此选项意味着您无法使用客户使用的库。这意味着您的库将更重很多,并包括有效的重复代码和数据。
希望可以帮助您了解要求如何工作以及其他人如何使用您的图书馆。
我终于使用了这种方法
<script src="http://mydomain/js/require.js"></script>
<script>
requirejs.config({
baseUrl: 'http://mydomain/js'
});
require(['main'],function(){
// here users can do anything they want as all required libraries are loaded
});
</script>
main.js
加载了require
指令,而不是使用脚本标签中的data-main
属性,这提供了一个回调,用户可以在其中放置其代码。