我的本地文件系统上有一个名为moment.js的文件,并按如下方式加载,其中包含require.js:
initialize: function() {
require(['moment'], function(data) {
console.log(data);
});
}
但是,如果我这样做:
initialize: function() {
require(['http://momentjs.com/downloads/moment.min.js'], function(data) {
console.log(data);
});
}
数据未定义。为什么是这样?以及如何在运行时动态包含远程模块?
答案 0 :(得分:7)
我注意到您尝试将模块名称加载硬编码为moment
的代码,因此请在现场配置RequireJS,以便您可以要求使用相同的名称:
initialize: function() {
require.config({
paths: { moment: 'http://momentjs.com/downloads/moment.min' }
});
require(['moment'], function(data) {
console.log(data);
});
}
答案 1 :(得分:0)
我认为url for moment应该没有文件扩展名,即它应该如下所示: 力矩:' http://momentjs.com/downloads/moment.min'
答案 2 :(得分:-2)
如果您需要在本地和从远程URL加载模块,则定义时命名模块,并添加一个名为“alias”的模块像URL一样,两个模块都在相同文件中定义。
示例:
//define a module NAMED "moment" using the first optional name paramter
define("moment", ["require"], function (require) {
/*module code goes here*/
});
//alias module to use when lazy loading from URL
define("http://momentjs.com/downloads/moment.min.js", ["require"], function (require) {
return require("moment");//returns original module
});
您可以在我撰写here的博文中了解更多相关信息。