public
Last active

Add AMD/define() support to NodeJS

  • Download Gist
define-node.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
var currentModule, defaultCompile = module.constructor.prototype._compile;
module.constructor.prototype._compile = function(content, filename){
currentModule = this;
try{
return defaultCompile.call(this, content, filename);
}
finally {
currentModule = null;
}
};
define = function (id, injects, factory) {
if (currentModule == null) {
throw new Error("define() may only be called during module factory instantiation");
}
var module = currentModule;
var req = function(relativeId){
if(relativeId.charAt(0) === '.'){
relativeId = id.substring(0, id.lastIndexOf('/') + 1) + relativeId;
while(lastId !== relativeId){
var lastId = relativeId;
relativeId = relativeId.replace(/\/[^\/]*\/\.\.\//,'/');
}
relativeId = relativeId.replace(/\/\.\//g,'/');
}
return require(relativeId);
};
if (!factory) {
// two or less arguments
factory = injects;
if (factory) {
// two args
if (typeof id === "string") {
if (id !== module.id) {
throw new Error("Can not assign module to a different id than the current file");
}
// default injects
injects = ["require", "exports", "module"];
}
else{
// anonymous, deps included
injects = id;
}
}
else {
// only one arg, just the factory
factory = id;
injects = ["require", "exports", "module"];
}
}
id = module.id;
if (typeof factory !== "function"){
// we can just provide a plain object
return module.exports = factory;
}
var returned = factory.apply(module.exports, injects.map(function (injection) {
switch (injection) {
// check for CommonJS injection variables
case "require": return req;
case "exports": return module.exports;
case "module": return module;
default:
// a module dependency
return req(injection);
}
}));
if(returned){
// since AMD encapsulates a function/callback, it can allow the factory to return the exports.
module.exports = returned;
}
};

Kris,

After running in to some problems with requirejs's node shim, I am looking in to using this shim instead. In my first tests, everything seems to be working out alright, and so I would like to inquire as to the licensing status of this piece of code. Can you add a license to the top of this file so that I can use it guilt free?

Thanks for taking the time to write this,

Nick

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.