Skip to content

Instantly share code, notes, and snippets.

@weepy
Created January 8, 2014 15:30
Show Gist options
  • Select an option

  • Save weepy/8318556 to your computer and use it in GitHub Desktop.

Select an option

Save weepy/8318556 to your computer and use it in GitHub Desktop.
// CommonJS require()
// monkey patched from version in visionmedia/mocha
// https://raw.github.com/visionmedia/mocha/master/mocha.js
// (which was in turn based on original by weepy #justsaying)
// added lines are commented
function require(p) {
var path = require.resolve(p)
, mod = require.modules[path];
// weepy: following line added
if (!mod) mod = require.load(path);
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
// weepy: added __filename and __dirname
var bits = path.split('/')
, __filename = bits.pop() + '.js'
, __dirname = bits.join('/')
mod.call(mod.exports, mod, mod.exports, require.relative(path), __filename, __dirname);
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path
, reg = path + '.js'
, index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function(p){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/')
, segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
// weepy: following added
require.load = function( path ) {
var request = new XMLHttpRequest();
console.log("trying to load", path + ".js")
request.open('GET', path + '.js', false);
request.send();
var text = "require.register('" + path + "', \
function(module, exports, require, __filename, __dirname) {\n\n"
+ request.responseText + "\n\n\
}); //@ sourceURL=" + path + '.js';
try {
(function(text) {
return window["eval"].call(window, text)
})(text)
}
catch(e) {
if(window.PARSEJS) {
try {
PARSEJS.parse(text)
} catch(e) {
console.error('Syntax error in file ' + path + ' at line:' + e.line + ', col:' + e.col + '. ' + e.message) //, e.stack) //, e)
}
} else {
console.error( "Syntax Error in file " + path + ": " + e.toString() )
}
}
return require.modules[ path ];
}
window.require = require;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment