javascriptjquerytwitter-bootstrapbrowserifybrowserify-shim

browserify-shim difference between alias and varName = require("module")


I'm using browersify-shim to bundle jquery, bootstrap, and my custom js files into one final package.

My custom js files don't have any dependency on jQuery, although bootstrap does.

I've have the following package.json

"browser" : {
    "jquery": "path/to/jquery",
    "bootstrap": "path/to/bootstrap"
},
"browserify": {
    "transform": [ "browserify-shim" ]
},
"browserify-shim": {
    "jquery": "$",
    "bootstrap": {"depends" : "jquery:jQuery"}
},

Now in my script file I have to do the following:

require('jquery');
require('bootstrap');

Is there a difference between adding an alias to "jquery" in package.json, vs doing var window.$ = require('jquery');

In some places I've seen people are doing both of the above, shouldn't only one be enough?

Secondly, why do I need to explicitly require both jQuery and bootstrap, even if none of my custom js files depend on it. Is there a way to tell browserify-shim to just bundle up everything in package.json, I'm anyway telling all the dependencies and aliases there. Why the duplicate effort to require each module in my script file.


Solution

  • First question:

    Is there a difference between adding an alias to "jquery" in package.json, vs doing var window.$ = require('jquery');

    The reason people do this is in the case where they need jQuery to be present outside their bundle.js. For instance, you might have a $(document).ready() handler directly in your index.html, in which case you'd need jQuery available on the window object. If you don't have any jQuery code outside of bundle.js then this isn't necessary and you can just use var $ = require('jquery'); as necessary in bundle.js.

    Your second question makes me think that the above is potentially the case. The answer is you can absolutely load Bootstrap and jQuery outside your bundle.js.

    A good solution here is to simply add them outside your bundle in the usual way, via a <script></script> tag. Then in the event you need them in your bundle, you can require them as a global so that if you reference them in bundle.js they don't get loaded twice.