How can I 'require' CommonJS modules in the browser? [closed]
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 code.
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.js or connect application. 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: There isn't any need for a build script as you always deal with the built code.
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)
Use Browserify.
Its description is: "Browser-side require() for your node modules and npm packages" which sounds what you need.
The CommonJS compiler.
Why? It works fine with Node.js (CommonJS) modules /treat module exactly as Node.js and, with UMD, brings minimum extra code to the compiled JavaScript, allows exporting global variables of third-party libraries without touching their code, source maps and a trick that other cannot do:
var str = require( "lorem-ipsum.txt" );
console.log( str );
Output:
Lorem ipsum dolor
sit amet, consectetur
adipiscing elit. Morbi...
Here are the slides: https://speakerdeck.com/dsheiko/modular-javascript-with-commonjs-compiler