browserify, jquery, and jquery plugins

i’ve been playing around with browserify and i’m still debating whether or not it’s really the next big thing for me. complicating my development with a build process needs to buy me something that i really want. the whole concept of browserify is to be able use commonjs modules in the browser by bundling all of your dependencies together. what does that really mean? it means that your server side and client side code can look very, very similar. in fact, you can even use the same node modules that you used on the back end in the front end.

this lets you write code that looks like:

to be able to work out all of the dependencies that your javascript has, a grunt task is introduced to scan through your javascript and include all of the dependencies found within your “require”d code.

that spoke to me quite a bit because i liked the fact that my front and back end code now looked very similar. but then i ran into a hiccup. what about jquery? it turns out that jquery works reasonably well if you just require it, but where i got stuck for a while is what if you wanted to use a jquery plugin?

i’m not completely sure that this is the right way to do it, but it works:

what’s different? binding $ and jQuery into global scope seems to be the key here. and actually, all you really need is window.jQuery, but I like having $ in global scope so i throw that in. but the question is why does this work?

if you look at any jquery plugin boilerplate, what it looks like is:

the plugin is expecting to find the jQuery object in global scope. usually, when jquery is included in the page, this happens automatically, but because of the way that jQuery is loaded via browserify, this isn’t happening. so the above hack just inserts it into global scope so that the plugin can find what it wants to then define itself.

it all seems to make sense, but it feels like there’s got to be a better way to do it. i just can’t figure out what that better way is. but i can’t get over the fact that it feels dirty to me that i need to write additional code just because i’m using browserify. it just feels like i’m doing something wrong here.

4 thoughts on “browserify, jquery, and jquery plugins

Leave a Reply

Your email address will not be published. Required fields are marked *