Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 664
B T Avatar asked Oct 22 '22 03:10

B T


1 Answers

uRequire is the perfect tool for this requirement, it's all about interoperability between the module formats and their incompatibilities.

Essentially uRequire converts or translates modules from nodejs to AMD and vise versa, plus the UMD format that runs on both nodejs and the browser or a combined .is that requires no AMD loader on browser.

It will require a build step though, but that is a minor concern in contrast to the offering.

like image 147
Angelos Pikoulas Avatar answered Oct 27 '22 10:10

Angelos Pikoulas