I’m using browserify in my WordPress theme. The problem I’m having is that I would like to include jQuery the “WordPress way” (i.e. wp_enqueue_script('jquery')
) so that all WordPress plugins that rely on window.jQuery
to be defined (and included in <head>
) keep working.
I’ve managed to make browserify ignore jQuery requires simply by setting browserify(conf).ignore('jquery')
in my Gulpfile.js but this results in scripts attempting to include jQuery the “browserify way” to fail.
How can I have a global jQuery object (included in its own <script>
element in head) so that WP plugins work, and still have code that does var $ = require('jquery')
work? Is it possible?
Update: I think I’ve gotten somewhat closer. I’m now including jQuery “normally” in <head>
. I’ve set ignore('jquery')
on my browserify call to avoid it ending up in my bundled file too AND I’m using browserify-shim (here’s where I’m slightly lost) to (I think?) make it so that when you do require('jquery')
it instead uses the global window.jQuery
object?
This seems to work in my own code, if I do:
var foo = require('jquery');
console.dir(foo);
I do get a jQuery object, and yet my bundled file is only a few kb’s indicating jQuery is not bundled in there. However, when I npm install jquery-cycle
and require that from my script, I get a JS error from the jquery cycle code that $ is undefined. The strange part imo is that the cycle script does exactly what I did, that is var $ = require('jquery')
but in there $
is not a jQuery object at all, instead just an empty object. Why is this?
Update 2: For some reason, if I change my require()
of the cycle plugin to instead require the exact JS file it works. IE I’ve changed require('jquery-cycle')
(which threw an error basically saying $ is undefined
) to require('../node_modules/jquery-cycle/index.js')
.
I would of course very much prefer to keep requiring things the “normal” way. Any ideas why that refuses to work?
Update 3: After much digging I’ve finally found that one needs to set global: true
to the transform()
call in order for dependencies dependencies to also use the shimmed jQuery. I finally found this solution here: Shimming dependencies of dependencies with browserify-shim
If you have multiple jQuery on the page you have to add a global variable: