1. So, you want to use require() in the browser…

    You’ve written a bunch of JavaScript or CoffeeScript running on Node, which has helped you organize your code into modules, develop a test suite in any of numerous styles, experiment in a decent REPL, and take advantage of useful libraries.

    Now you want to deploy that code to the final frontier—the web browser.

    You have a couple options. A couple dozen, actually. Here are just the libraries that were easy to find, in order of GitHub popularity. The bars represent their number of watchers:

    As you can see, quite a few developers have approached this problem. There are several ways to interpret this:

    • Maybe it’s an easy problem to solve, since so many people have opted to roll their own.
    • Maybe it’s hard to solve, since so many people evidently decided that the others got it wrong.
    • Maybe each person has legitimately different requirements.
    • Maybe it’s just “opinionated”, like web frameworks.

    Downloading code on-demand: related, but different.

    Admittedly, several of these libraries are trying to solve a related, but different problem: downloading the required modules on-demand (usually asynchronously via AJAX).

    While an interesting problem to tackle, I think using this scheme in production is a bit misguided. Compiling your entire application into a single JavaScript file shouldn’t be a problem for anyone. Whose minified and compressed code is bigger than the size of a few JPEGs? (Hint: not Facebook’s, Grooveshark’s, or Pandora’s.) At most you should need a tiny loader script that grabs a couple of large, self-contained blobs of code when the page loads.

    Loading dozens of small modules on demand is just going to result in more HTTP requests and worse compression. The simpler alternative is to already have the modules available, and just run them and return their exports on-demand. Thus, you have one file and no asynchrony.

    Deploying the same code to production that you run in development: the actual problem.

    The larger and more compelling use-case that many of these libraries tackle is running the same code in the browser that you wrote for Node. The foremost obstacle here just happens to be the organization of code into CommonJS-like modules. Even if you avoid using Node’s core modules and globals like process and __filename, the use of require for your own modules still must be addressed.

    That’s where these libraries come in.

    I happen to have implemented yet another one of these libraries for my own purposes, so I’m familiar with the problem. In my next blog post, I’ll explain what requirements the most popular libraries satisfy, describe where they fall short, and demonstrate some improvements we could make to truly call them production-ready.

    Discuss this post on Hacker News.

Notes

  1. chetteserver reblogged this from exogen
  2. exogen posted this