我正在使用browserify通过CommonJS样式的依赖项来捆绑我的前端javascript。例如,我有:
$ = require('jquery/dist/jquery'); // v2.1.0-beta2
_ = require('underscore');
Backbone = require('backbone');
但是,当browserify捆绑依赖项时,我遇到以下控制台错误:
Error: jQuery requires a window with a document
查看jQuery代码,我发现它正在尝试this
用于global window
。
(function( window, factory ) {
....
}(this, function( window ) {
由于browserify包装了所有依赖关系,因此this
是object
,而不是window
。
有趣的是jQuery> = 2应该与CommonJS兼容。但是,问题是browserify如何包装依赖项。有谁解决了这个问题?
就您而言,它应该像使用一样简单;
$ = require('jquery/dist/jquery')(window); // v2.1.0-beta2
可能很明显;但您必须在使用的每个模块中使用这种形式的声明(传递window
给的结果require
),而不仅仅是一个/第一个,等等。
对于任何想知道为什么的人,处理这个的jQuery中有趣的代码是:
(function( window, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// Expose a jQuery-making factory as module.exports in loaders that implement the Node
// module pattern (including browserify).
// This accentuates the need for a real window in the environment
// e.g. var jQuery = require("jquery")(window);
module.exports = function( w ) {
w = w || window;
if ( !w.document ) {
throw new Error("jQuery requires a window with a document");
}
return factory( w );
};
} else {
factory( window );
}
// Pass this, window may not be defined yet
}(this, function( window ) {
// All of jQuery gets defined here, and attached to the (locally named variable) "window".
}));
请注意顶部的注释,这些注释显式地解决了browserify;在jQuery位于CommonJs-land的情况下jQuery
,它返回一个函数,该函数在传递对象(应为window
)时返回jQuery ,而不是返回我们所知的函数。
混淆问题的进一步,这个安装程序代码已经在最新的再次改变提交,使module.exports
被确定像这样;
module.exports = global.document ?
factory( global ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
......这样的,如果this
是的window
对象时,jQuery是require()
“d,它会返回一个jQuery的情况下,如果没有它会返回出厂功能之前; 因此,当实际释放2.1.0版本时,您将不得不(window)
再次删除该呼叫。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句