Tuesday, 6 August 2013

How to use CommonJS and AMD side by side in node.js

How to use CommonJS and AMD side by side in node.js

I've been researching CommonJs, AMD, module loading, and related issues
for over a week. I feel like nothing out there does what I need. My basic
need is to share code seamlessly between frontend and backend. There are
various issues around this including module formats for the client side,
script loading, and module format conversions/wrapping. The piece I've
been struggling with recently is how to use both CommonJS and AMD (or
something AMD-like) in node.js.
You can't get away from commonJs in node.js, so my thinking is that if I
want to use AMD, it has to work alongside commonJs. What tools, libraries,
or techniques can I use to get something AMD-like working?
For example, I would like to be able to write a module like this:
var x = require('x')
modules.exports = function(a, callback) {
if(a) {
require(['y','z'], function(y,z) {
callback(x, y.o + z.k)
}
} else {
callback(x, "ok")
}
}
Ideally:
Both node.js and the amd-like modules will have paths interpreted in the
node.js way (paying attention to node_modules unless the module path
starts with "/", "./", or "../")
doesn't require source conversion for the server side in a build step (ie
modules will run in node.js without each one being programmatically
converted)
module or require don't need to be explicitly passed into the amd-like
require function

No comments:

Post a Comment