Friday, 12 May 2017

What's the point of using browserify-shim, and why is having a required module run globally such a bad thing?

I'm trying to understand what browserify-shim is, because I'm having trouble getting browserify to play nice with some AngularJS plugins that rely on other plugins. For example, angular-moment, which depends on angularjs and momentjs.

So far, what I've been doing is just doing the following on my vendor.js file;

window.angular = require('angularjs');
window.$ = require('jQuery');

and then just asumed that it would be available globally everywhere else. This works great, and honestly this leaves me thinking what's the point of browserify-shim existing if I can get the same results this way. I'd consider browserify-shim better if it actually allowed my global variables to be present on all my files implicitly, but it still forces me to write var dependency = require('dependency') everywhere, making for some very tedious to write code.

Also, while this solution works, it's still very problematic for me for javascript libraries that expose more than one variable globally. So for the last week or so, I've been searching for methods on how to get specific modules to run globally so they can expose all the global variables they need to expose.

Recently however, I've read this as part of the "Browserify Shim handles the following real-world use cases" on the browserify-shim docs:

Modules that just declare a var foo = ... on the script level and assume it gets attached to the window object. Since the only way they will ever be run is in the global context — "ahem, … NO?!"

My question is, why this this such a terrible thing? I understand the potential dangers of this, but if I know I'm requiring a library I trust, why can't I decide to require it globally? Is there truly no easy way to just do something like this and expect it to work?

window.angular = require('angularjs');
window.moment = require('moment');
window.moment = require('./../../node_modules/moment-timezone/builds/moment-timezone-with-data-2010-2020');
require('angular-moment');

Also, do note that the code above does NOT work, mainly because for some reason, angular-moment isn't finding the global window.moment object with the timezone plugin attached. A problem that would not exist if I could require momentjs and the timezone plugin globally.



via sgarcia.dev

No comments:

Post a Comment