4

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

"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"]

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.

Encore PTL
  • 8,084
  • 10
  • 43
  • 78
  • Hey it would help if you posted your package.json file. Also, you might want to check out http://stackoverflow.com/questions/24827964/browserify-with-twitter-bootstrap/24834257 which has a fairly similar question+answer. – urban_raccoons May 11 '15 at 17:44
  • That did not help. I am able to build the bundle fine but issue when running karma tests – Encore PTL May 13 '15 at 15:34
  • Is this possible. To expose jquery to window.jQuery so that other module that is loaded using require can reference window.jQuery – Encore PTL May 13 '15 at 17:36
  • If you don't provide any of your code and a more detailed explanation of how you have things set up, no one is going to be able to help you – urban_raccoons May 17 '15 at 03:56

1 Answers1

5

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.

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

"jquery: $"

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

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.

YPCrumble
  • 26,610
  • 23
  • 107
  • 172
  • Related: . I had this issue attempting to create a `bundle.js` including Semantic UI with Browserify, and `window.jQuery = require("jquery");` was sufficient to fix it. – TheDudeAbides Oct 16 '19 at 02:36