简体   繁体   中英

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

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.

You could check out, http://dojotoolkit.org/documentation/tutorials/1.9/node/ I've only played with it a little, but has worked with what I've tried. I got it working with node-orm and remember that being a pain to get going, but might of just been me making a mess while playing with it.

Essentially you end up with AMD on the server, like:

require(["dojo/node!orm","other/amd/module"], function(orm){
    //use third party commonjs module and your own amd modules here
}

It looks like you've already investigated Requirejs's suggestion to wrap commonjs modules in an AMD require (automatically during build most likely using r.js).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM