How do I use Browserify with external dependencies?

cobbdb picture cobbdb · Apr 17, 2014 · Viewed 27.4k times · Source

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?

Answer

katranci picture katranci · Apr 17, 2014

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 $);
  1. Install browserify-shim:

    npm install browserify-shim --save-dev
    
  2. In package.json file, tell browserify to use browserify-shim as a transform:

    {
        "browserify": {
            "transform": [ "browserify-shim" ]
        }
    }
    
  3. In package.json file, tell browserify-shim to map jQuery to the jQuery in the global scope:

    {
        "browserify-shim": {
            "jQuery": "global:jQuery"
        }
    }
    
  4. Run browserify

    browserify mymodule.js > bundle.js
    

If you examine bundle.js you will notice that require('jQuery') is replaced with (window.jQuery).