I am trying to slowly introduce Browserify into my site, but I don't want to rewrite all the js and I don't want duplicate instances of jquery and other libraries bundled with my Browserify build.
If I build my module listing jquery as an external dependency, how do I then point it at my global jquery instance? Also the goal is to eliminate the mylibs global (example below), so I don't want to use it in my module.
This is what I'm trying to do (psudo-code). This would be in my site's repo - not the module's. The module would be installed with Bower:
var mylibs.jQuery = $.noConflict(); // global used by lots of existing code
module.exports = {
jquery: mylibs.jQuery // can be imported by my module as require('jquery')
};
Something like that is what I'm trying to achieve. Is this possible?
You can achieve that by using browserify-shim. Assuming that you've got a module named mymodule.js
that depends on jQuery in the global scope with the following contents:
var $ = require('jQuery');
console.log(typeof $);
Install browserify-shim:
npm install browserify-shim --save-dev
In package.json file, tell browserify to use browserify-shim as a transform:
{
"browserify": {
"transform": [ "browserify-shim" ]
}
}
In package.json file, tell browserify-shim to map jQuery to the jQuery in the global scope:
{
"browserify-shim": {
"jQuery": "global:jQuery"
}
}
Run browserify
browserify mymodule.js > bundle.js
If you examine bundle.js you will notice that require('jQuery')
is replaced with (window.jQuery)
.