Jquery plugins and Browserify don't always play nice with each other. Sometimes the plugin author requires jQuery in such a way that they do not modify the same jQuery object which your code is using.
This transform will change all instances of require('jquery')
to window.jQuery || require('jquery')
, meaning that if you declare a global jQuery object at the top of your code this will get used wherever require('jquery')
is called. If no global object is declared the module will just require jQuery as normal.
// index.js
(function(undefined) {
"use strict";
// Declare global.jQuery object
global.jQuery = require("jquery");
// Require jQuery plugins
require("utils/jquery.elemental").init();
require("utils/jquery.animate-css");
require("jquery-sticky-kit");
require("jquery-inview");
...
runMyApp();
})();
// gulpfile.js
var bundler = browserify({
entries: [jsSrcDir + "/index.js"],
...
});
bundler = bundler
.transform("babelify", {
presets: [
["env"]
],
})
...
.transform("browserify-jquery-transform", {
global: true
});
This was created to solve a problem in a specific app. Messing with a third-party modules expected jQuuery object may cause unexpected behaviour. Use with Caution!