I find libraries such as Require.js to be too complicated to trust them.
I put all my client-side JS files into ./src directory and watch them with Node.js server. When any file in ./src is added or modified then server automatically copies it to ./build directory and wraps it with additional code required by module loader.
This way I can use (almost) the same syntax for handling modules on both client- and server-side, e.g. I can write client-side script which looks like this:
var button = require('widgets/button.js').button;
var toggleButton = Object.extend(button, {
label: 'Toggle me',
});
exports.toggleButton = toggleButton;
There's a tradeoff here, which is that you'll have to stick to a strict subset of conventional Node. Not just the builtin libraries (fine, that's expected), but basic conventions.
For instance, your approach doesn't support assigning to `module.exports` (just a few more lines of code), relative paths (a few dozen more lines), or the path resolution used by `require.resolve` (a few dozen more).
For small apps it's probably fine, and I've used something very similar. But it's not always easy to decide "this will be a small app" up front. And then there's the issue that even if your app is small, `require` will be doing something very different in Node (complex path resolution) than in the browser, and it could lead to confusing results or a lying test suite.
I put all my client-side JS files into ./src directory and watch them with Node.js server. When any file in ./src is added or modified then server automatically copies it to ./build directory and wraps it with additional code required by module loader.
This way I can use (almost) the same syntax for handling modules on both client- and server-side, e.g. I can write client-side script which looks like this:
And it will automatically get compiled into: The client-side framework for handling such modules takes 28 lines of code: https://gist.github.com/1287050Unless you are writing really large apps, this approach seems to be much cleaner, just remember to combine and minify all modules before deployment.