使用Browserify时获取“未捕获的ReferenceError:jQuery未定义”

时间:2021-10-31 19:06:52

I am using browserify in my project and trying to require a module which require jQuery as a global variable. I used browserify-shim which I set to one of these one at a time

我在我的项目中使用browserify并尝试需要一个需要jQuery作为全局变量的模块。我使用了browserify-shim,我一次设置为其中一个

"jquery": "global:$"

"jquery": "global:jQuery"

"jquery": "$"

"jquery": "jQuery"

and still nothing seems to work. The library using global jQuery is also in the shim and set to "depends": ["jquery"]

似乎仍然没有任何效果。使用全局jQuery的库也在垫片中并设置为“depends”:[“jquery”]

Browserify makes the concatenated Javascript bundle correctly but I get this error Uncaught ReferenceError: jQuery is not defined when running karma tests. I have the same browserify-shim config specified in the karma.conf.js. How can I set the jQuery to be global so that it can access it and not throw this error.

Browserify正确地使用连接的Javascript包但是我得到了这个错误未捕获的ReferenceError:运行karma测试时没有定义jQuery。我有相同的karma.conf.js中指定的browserify-shim配置。如何将jQuery设置为全局,以便它可以访问它而不会抛出此错误。

1 个解决方案

#1


Browserify-shim assumes you're using Browserify to shim non-global variables. That's somewhat the point of Browserify, that you don't pollute the global scope or redefine things on the global scope.

Browserify-shim假设您使用Browserify来填充非全局变量。这有点与Browserify有关,您不会污染全局范围或重新定义全局范围内的事物。

The solution in your case is to use this version of declaring jQuery:

您的案例中的解决方案是使用此版本的声明jQuery:

"jquery: $"

...in your package.json, and then explicitly define the global somewhere in your code, via either:

...在您的package.json中,然后通过以下任一方式在代码中的某处显式定义全局:

window.$ = require('jquery');

...or simply...

$ = require('jquery'); // Note no `var` here.

That will allow you to use require('jquery') in your javascript bundles, but also use jQuery directly in things like templates via global scope.

这将允许您在javascript包中使用require('jquery'),但也可以通过全局范围直接在模板之类的东西中使用jQuery。

#1


Browserify-shim assumes you're using Browserify to shim non-global variables. That's somewhat the point of Browserify, that you don't pollute the global scope or redefine things on the global scope.

Browserify-shim假设您使用Browserify来填充非全局变量。这有点与Browserify有关,您不会污染全局范围或重新定义全局范围内的事物。

The solution in your case is to use this version of declaring jQuery:

您的案例中的解决方案是使用此版本的声明jQuery:

"jquery: $"

...in your package.json, and then explicitly define the global somewhere in your code, via either:

...在您的package.json中,然后通过以下任一方式在代码中的某处显式定义全局:

window.$ = require('jquery');

...or simply...

$ = require('jquery'); // Note no `var` here.

That will allow you to use require('jquery') in your javascript bundles, but also use jQuery directly in things like templates via global scope.

这将允许您在javascript包中使用require('jquery'),但也可以通过全局范围直接在模板之类的东西中使用jQuery。