我正在使用requirejs,并且在我的一个文件中,下划线是依赖项。下面是包含下划线的一段代码。Underscorejs与requirejs一起使用时返回undefined
define(["lib/underscore"], function(_) {
// Here _ is undefined
});
通过一些研究,我发现下划线将它添加到全局命名空间中。 Underscore返回undefined,这就是为什么_变得未定义。如果我用下面的方法_是有效的。
define(["lib/underscore"], function() {
// Here _ is defined
};
在上面的代码中,我不覆盖添加到全局名称空间的_。
在我的探索,找出原因下划线不返回_我发现underscore.js
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
下划线时通过requirejs它应该返回加载它意味着这下面的一段代码_,而不是不确定的。这不会发生在我身上。任何人都可以帮助我这个。
1.当下划线被调用时,define存在,我在下划线之前加载RequireJS。 2.路径也是正确的我能够调试到我上面指定的代码。 – kishore
@kishore Underscore将自己注册为*一个已命名的模块*。这意味着*应该按名称引用,而不是路径*引用。我答案中的第一个重点应该解决这个问题。 – Joseph
所以我必须在requirejs config中定义一个路径 – kishore