Question

I have created a JavaScript library which can be used for logging purposes.
I also want to support the logging of requirejs.
Which functions/events of requirejs can I prototype/wrap so I can log when a module is initialized and when it is done initializing and returns the initialized object.

For instance if I call require(["obj1","obj2", "obj3"], function(obj1, obj2, obj3){}
I would like to know when requirejs begins on initializing each of the object, and I would like to know when each object is completely initialized.
I looked into the documentation/code, but could not find any usefull functions I can access from the requirejs object or the require object.

Note: I do not want to change the existing code of requirejs I wish to append functionality from the outside by either prototyping or wrapping.

What I have tried (problem is that this only accesses the begin and end of the entire batch of modules):

var oldrequire = require;

require = function (deps, callback, errback, optional) {
    console.log("start");
    var callbackWrapper = callback;

    callbackWrapper = function () {
        console.log("end");
        var args = new Array();
        for(var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        callback.apply(this, args);
    };
    oldrequire.call(this, deps, callbackWrapper, errback, optional);
};
Was it helpful?

Solution

This is a "better than nothing answer", not a definitive answer, but it might help you look in another direction. Not sure if that's good or bad, certainly it's brainstorming.

I've looked into this recently for a single particular module I had to wrap. I ended up writing a second module ("module-wrapper") for which I added a path entry with the name of the original module ("module"). I then added a second entry ("module-actual") that references the actual module which I require() as a dependency in the wrapper.

I can then add code before and after initialization, and finally return the actual module. This is transparent to user modules as well as the actual module, and very clean and straightforward from a design standpoint.

However, it is obviously not practical to create a wrapper per module manually in your case, but you might be able to generate them dynamically with some trickery. Or somehow figure out what name was used to import the (unique) wrapper module from within it so that it can in turn dynamically import the associated actual module (with an async require, which wouldn't be transparent to user code).

Of course, it would be best if requirejs provided official hooks. I've never seen such hooks in the docs, but you might want to go through them again if you're not more certain than me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top