Requirejs 通过绝对路径加载时未定义依赖项
我有这样一些模块:Requirejs 通过绝对路径加载时未定义依赖项,requirejs,Requirejs,我有这样一些模块: define('hello',[], function() { return { say: function(word) { console.log("Hello, "+word) }, }; }); 我这样使用它(没有任何require.config): 到目前为止,一切顺利 但是,当我试图要求具有绝对路径的相同模块时,我的依赖模块未定义: require(["http://example.com/js/hello.js"], function(hello
define('hello',[],
function()
{
return {
say: function(word) { console.log("Hello, "+word) },
};
});
我这样使用它(没有任何require.config):
到目前为止,一切顺利
但是,当我试图要求
具有绝对路径的相同模块时,我的依赖模块未定义:
require(["http://example.com/js/hello.js"],
function(hello)
{
console.log("main",hello);
hello.say("main");
});
控制台:
main undefined
Uncaught TypeError: Cannot read property 'say' of undefined // Oops!
为什么会这样?命名模块(define(“NAME”,[…],function(){…})
)是在确切的名称下需要的。当URL需要它时,它会被正确加载,但会以“期望的”名称注册,之后requirejs会失去跟踪,仍然在寻找名称为http://example.com/js/hello.js
指定给define()
的名称没有被所需模块的名称覆盖的原因是允许多个模块定义在文件中共存,例如在优化之后。优化器将所有define调用转换为具有显式名称的表单
绝对名称未转换为模块id的原因是无法进行此转换。requirejs的所有配置选项都决定了如何将模块id转换为脚本位置,而不是反过来
:
这些通常由优化工具生成。您可以自己显式命名模块,但这会降低模块的可移植性。。。通常,最好避免在模块名称中进行编码,只需让优化工具在模块名称中燃烧即可
匿名模块,即:
定义([],
函数()
{
返回{
say:function(word){console.log(“Hello,”+word)},
};
});
可与模块id(“hello”)或绝对路径一起使用,因为它最初注册时没有名称,后来收到所需的名称。谢谢您的全面回答
main undefined
Uncaught TypeError: Cannot read property 'say' of undefined // Oops!