It\'s already possible to convert commonjs modules to requirejs, but I still want to know whether it\'s possible to do the reverse. Is there any way to convert requireJS modules
Yes its possible if you use uRequire, a tool I wrote specifically for javascript module format conversion - AMD/Requirejs --> commonjs/nodejs and back (plus more).
It seems as a trivial AST manipulation & dependencies resolution @ start, but module formats are incompatible in many ways apart from syntax:
dependency/path resolution : commonjs uses fileRelative (eg '../PersonModel') whereas AMD can also use package-relative (eg 'Models/PersonModel')
execution environment: commonJs modules are loaded synchronously, whereas AMD are loaded asynchronously (AMD also has the asynchronous require
version require(['dep1', dep2'], function(dep1, dep2){})
as its targeted mainly for the browser).
These are also other differences (eg AMD loader plugins) but in general writing against each one 'locks' you in that format. .
uRequire enables you to author in AMD or commonJS and convert to the other easily (or convert to UMD), hence enjoying modular Javascript without the boilerplate.
Manually, it should be possible.
A require.js module looks like:
define('module', ['dep1', 'dep2'], function(dep1, dep2) {
return myFunction = function() {
};
});
Exporting to a CommonJs module shouldn't be too hard:
var dep1 = require('dep1');
var dep2 = require('dep1');
exports.myFunction = function() {
};
You don't have to return a function, it can be an object too:
define('module', ['dep1', 'dep2'], function(dep1, dep2) {
return {
myFunction1: function() {
},
myFunction2: function() {
}
};
});
...
var dep1 = require('dep1');
var dep2 = require('dep1');
exports.myObject = {
myFunction1: function() {
},
myFunction2: function() {
}
};
Edit: converting is also possible.
Yes, it is possible. Many sites including Sound Cloud have developed their own conversion tool.
Mozilla has developed a nice little module called SweetJS. Basically allows you to define macros in JavaScript. To use in Node.js, you'll need to use it's binary to actually use the macros, as it's not available through runtime.
http://sweetjs.org/
EDIT:
Yehuda, one of the developers of Ember.js has released a transpiler module.
It is written in Ruby, and not JavaScript, but perhaps someone will convert it over. Nonetheless, you can use it within Node.js by forking a ruby process.