Override the require function Override the require function javascript javascript

Override the require function


var Module = require('module');var originalRequire = Module.prototype.require;Module.prototype.require = function(){  //do your thing here  return originalRequire.apply(this, arguments);};


Here is a much safer native ES6 answer based on @orourkedd which acts like an event listener on all require calls, It might look like its replacing require but if you look closer its actually saying: require = require and trap calls to it but return original behaviour. This is just one of the millions of uses of Proxy() which has been really handy for me, for example in Typescript for mapping tsconfig "paths" with the real module node will resolve.

I would go as far as to say that this is not "Monkey patching" as its on a lower level of the language.

var Module = require('module');Module.prototype.require = new Proxy(Module.prototype.require,{    apply(target, thisArg, argumentsList){        let name = argumentsList[0];        /*do stuff to ANY module here*/        if(/MyModule/g.test(name)){            /*do stuff to MY module*/            name = "resolveAnotherName"        }        return Reflect.apply(target, thisArg, argumentsList)    }})