UPDATE: replace require.js with 24 lines of unobtrusive Javascript

For a few weeks now I've been working on converting code that relies on an in-house Javascript dependency manager, to require.js. My current employer had already been doing this on one project when I started a month ago, and the innovation they've allowed me to introduce for accomplishing this on a different project, is to generate/transform the code with a node application. Good thing too because I've compared the projects and I'm dealing with close to 100 files, whereas the other project didn't entail even 20.

One problem endemic to Javascript dependency managers in general, which I've encountered with both the in-house version, and require.js, is lack of ease of debugging. Because files are dynamically included, break-points you set in files vanish when you do a (hard) refresh.

But there is another problem specific to require.js that our in-house dependency manager avoided, perhaps inadvertently: circular references. To quote the creator of require.js himself, James Burke, regarding circular references: "this is indeed a restriction"

Our in-house system avoided the problem by exporting all modules as globals. Absolutely sub-optimal of course, unless they are all organized within just one global object. Yeah, that's right, I'm suggesting the namespace pattern, not unlike the purported "solution" to the circular reference problem with require.js similarly suggesting creating a global "exports" namespace.

In any event, the in-house dependency manager therefore only required that modules be specified as requirements in an array, but unlike require.js did not also require that these same modules be passed into a callback function as an argument list, thereby violating DRY ("don't repeat yourself") In fairness I can think of a workaround to this, something such as:

(function() {
    var reqs = [x, y, z];

    require(reqs, //and return a function call with .apply(..., reqs) to pass the reqs as arguments
    ....

But now your code is turning into anything other than POJS (plain old Javascript):

  • It must be organized the way require.js requires
  • It must be hacked to avoid violating DRY
  • It must be hacked to solve the admitted problem of circular references

And even then, debugging is still problematic. All of which can be avoided through a) name-spacing and b) discipline, namely the discipline of:

  • Avoiding executable code outside of module methods
  • Allowing for a single entry point, specified in the last (of course) javascript file to be script/src'd

Since I've been adhering to the above for a number of years, now that I've seen the severe warts that require.js entails, I would never voluntarily use it until these issues get addressed. YMMV.


Dexygen: Software, Simple and Powerful