How to require CommonJS modules in the browser?


What is the best way to load CommonJS modules as client-side javascript in the browser?

CommonJS modules put their functionality in the module.exports namespace and are usually included using require(pathToModule) in a server-side script. Loading them on the client cannot work the same way (require needs to be replaced, asynchronousness needs to be taken into account etc.)

I have found module loaders and other solutions: Browserify, RequireJS, yabble, etc. or ways to simply alter the modules. What do you consider the best way and why?

9/27/2011 9:39:41 PM

Accepted Answer

I have used requirejs extensively in the past (implementation on BBC iPlayer in 2010) and it works well. It can handle CommonJS modules, but it needs an additional wrapper, which I find annoying. If you want to use those modules in node.js as well, you need to use requirejs on the server side as well, which I don't like doing since it is not idiomatic node.js JavaScript.

I have used webmake and browserify in the past year on a few projects. Initially, the compilation step put me off, but having used it extensively this year, I can say that this is not an issue.

Browserify has a watch function included, which works very well. Webmake can be hooked up to a watcher (such as watchr) or, you can use the webmake-middleware module, which can be used as part of an express or connect app. This has the advantage that rather than compiling the JavaScript on each save, it is only compiled when you actually request it. Connect makes it trivial to create a server (also static), so you could create a tiny static node.js server to serve up your files if you want to develop your frontend without a backend.

Bonus: no need for a build script as you always deal with the built code.

9/29/2012 3:53:05 PM

Here is a comprehensive list of your current options ordered by their respective popularity (number of watchers) on GitHub:

Options for use of require() in the browser (Wayback Machine archive)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow