Skip to content

Instantly share code, notes, and snippets.

@halfzebra
Created August 29, 2016 10:17
Show Gist options
  • Save halfzebra/c7192defa424ee7216b1aa38c52e4447 to your computer and use it in GitHub Desktop.
Save halfzebra/c7192defa424ee7216b1aa38c52e4447 to your computer and use it in GitHub Desktop.
Intercept requirejs calls and output info to console
// Alternative https://gist.github.com/nantunes/c4eb68c32843ccd43c7b
window.require = new Proxy(window.require, {
apply: function (target, thisArg, argumentsList) {
console.log('require call to \n ' + argumentsList[ 0 ].join('\n ') + '\n\n');
return target.apply(thisArg, argumentsList);
}
});
window.define = new Proxy(window.define, {
apply: function (target, thisArg, argumentsList) {
var args = argumentsList;
var deps = [];
var msg = '';
var stack = new Error().stack;
// Walk through the arguments and attempt to extract dependencies.
if (Array.isArray(argumentsList)) {
deps = argumentsList
.filter(function (val) {
return typeof val !== 'function'
})
.map(function (val) {
if (typeof val === 'string') {
return val;
} else if (Array.isArray(val)) {
return val.join(', ')
} else {
throw new Error();
}
});
}
// Intercept calls to local require.
if (typeof argumentsList[ 0 ] === 'function' && argumentsList.length === 1) {
var callbackWithLocalRequire = argumentsList[ 0 ];
var proxy = new Proxy(callbackWithLocalRequire, {
apply: function (target, thisArg, argsList) {
var args = argsList;
var localRequrie;
// Check if it's a localRequire.
if (argsList.length !== 0 && argsList[ 0 ].name === 'localRequire') {
localRequrie = argsList[ 0 ];
args = [].concat(
[
new Proxy(localRequrie, {
apply: function (target, thisArg, localRequrieArgumentList) {
if (localRequrieArgumentList.length === 1) {
console.log('localRequrie call to \n ' + localRequrieArgumentList + '\n\n');
} else {
console.log('localRequrie call to \n ' + localRequrieArgumentList[ 0 ] + '\n\n');
}
return target.apply(thisArg, localRequrieArgumentList);
}
})
]
, argsList.slice(1)
);
}
return target.apply(thisArg, args);
}
});
// Monkey-patch Proxy: http://stackoverflow.com/questions/38259885/function-proxy-tostring-errors
proxy.toString = Function.prototype.toString.bind(callbackWithLocalRequire);
args = [ proxy ]
}
// Prepare the output with a call stack.
if (deps.length !== 0) {
msg = stack.replace(/^Error/, 'define call with dependencies [ ' + deps.join(', ') + ' ]');
} else {
msg = stack.replace(/^Error/, 'define call');
}
msg = msg.replace(/\s+at Object.apply.*\)/, '');
console.log(msg + '\n\n');
return target.apply(thisArg, args);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment