Not only have we split our code up into separate module components, the secret to good application design, but we’ve also got dependency management, scope isolation and namespacing.
If you’ve ever used Node or Python, you’ve used CommonJS modules, whether you realize it or not. In a nutshell, CommonJS modules give you require and exports, letting you require other modules and expose variables to other modules. For example:
Properties are exported by either setting them on the
exports object, or by setting the
External modules are then imported in using the
require() function, setting the returned value to a local variable:
//= CoffeeScript MyClass = require('models/my_class')
If you’re not using Hem, but you are using Node.js, you should checkout Stitch, which will make sure all your libraries are stitched together into CommonJS modules, ready to run straight inside the browser.
Sprockets is another good alternative, and if you’re using Rails, it has the added advantage that it’s already baked into the asset-pipeline. Whilst it doesn’t use CommonJS modules, it does ensure that individual modules are executed inside a closure, localizing the context. A good half-way house.