Unlike in Node.js for example, JavaScript in browsers doesn’t come with a require function to load modules dynamically. There are some implementations which try to fill this hole, but as I’ve pointed out in my previous require() post none of them really fit my needs. What I want is a lightweight solution with full CommonJS compatibility and easy handling.
I was using my first require() version only in smaller contexts last year, so I was happy even though some things were missing, but now I’m working on a more complex JavaScript framework for my current project, which gave me the impulse to improve my old code to a full featured version:
- 100% CommonJS modules 1.0 compliant (all unit-tests passed)
- 99% CommonJS modules 1.1.1 compliant (didn’t find any tests to verify)
- improved security (but I’m sure it’s still not bullet proof)
- correct relative path handling (the old version was buggy)
- support for module bundles (I love this ^^)
I tried to improve security a bit by preventing modules from accessing the internals of the require function and by making require a read only property of window
. I’m pretty sure this makes require() a bit safer, but I didn’t spent to much time on this topic to be sure.
Instead I spent several iterations on a feature I really wanted to have for the new require: Bundles (not packages). A bundle is a single file, which represents a directory with multiple modules. Hence multiple modules can be loaded with one HTTP request, which can reduce the network traffic significantly. But more on this later…
Continue reading JS require() for browsers – better, faster, stronger