drogon
drogon

Reputation: 1825

Browserify - global vars

I'm a little confused on how Browserify works by default.

If I have a script that defines a global variable, such as in jQuery (window.$), and I call require('jquery'), wouldn't that variable automatically be assigned to the global scope? In that case, why would I need to manually assign that variable to the global scope in my code (i.e. window.$ = require('jquery'))?

Upvotes: 0

Views: 573

Answers (1)

Ghazgkull
Ghazgkull

Reputation: 980

When you use require(...) to bring in jQuery, it ends up getting defined within Browserify's enclosing scope just like any other module. You can assign it to a global variable as you're showing, but the recommended way to use it is to instead add the require() at the top of every module that needs jQuery... just like you would for any other module.

So rather than use a global $ variable, your dependent modules would add:

var $ = require('jQuery');

Edit: P.S. If you're loading jQuery asynchronously you'll run into the extra complication that the require(...) statements are evaluated aggressively before your asynchronously loaded script is available. I hit this recently and explain the solution I came up with here: How to use my own version of jQuery with browserified modules

Upvotes: 1

Related Questions