Node.js require() for your browser

Update: This article is obsolete. Check out my post “JS require() for browsers – better, faster, stronger” for an improved version, which is CommonJS compliant, more secure, handles relative paths correctly and supports module bundles. The require function described here is obsolete.

Everyone who has worked a bit with JavaScript will sooner or later wish for an easy way to load a script directly from another script (similar to #include in C or require() in PHP). Over time frameworks like RequireJS and some other code snippets bubbled up to the surface, but they all have some drawbacks: They either require quite a lot of extra code, only allow asynchronous loading (this is not always a good idea) or don’t separate the module from the rest of the code, which makes porting kinda difficult.

Then came Node.js with its easy to use module concept, which needs nothing more than a simple function call to load a JavaScript file into its own namespace. When I started to use Node.js this concept felt a bit odd at first, but once I got used to it I loved it an started to look for a way to bring Node.js’ require() to the browser. I stumbled uponĀ Browserify pretty fast, but didn’t take a closer look, since it simply looked like a bit too much for my use-case and all this command-line stuff just didn’t feel right.

In the end I started to implement my own require function for browsers, which resembles most of the features implemented in Node.js and also allows asynchronous loading. For the lack of creativity I simply called the project Require(). However, I’m sure it lacks some features of the bigger frameworks, but it’s just a small script (ZIP archive) and pretty easy to use as you can see on the example page, so I think it’s worth a try. Continue reading Node.js require() for your browser