KevBelisle
KevBelisle

Reputation: 225

Define execution context of external JS file?

I'm working on small JS library that I would like to be able to use in different projects.

My problem is the following: I need some data which is defined in a couple files from another JS project of which I do not control the source code. These files are structured as follows:

(function() {
  var exportObj;
  exportObj = typeof exports !== "undefined" && exports !== null ? exports : this;

  exportObj.??? = ...;

}).call(this);

Now, I can prevent global namespace pollution by defining an exports variable in the global scope. I can then rename it to whatever I want once the external files have loaded.

However, this won't work well if I ever need to work in parallel with another script that uses the exportObj = typeof exports ... pattern, as I would catch all the definitions from that script as well.

Is there anyway I can define the value of this that is used for the execution of the external JS files I need to include? That way I could redirect the definitions to a variable of my choosing, without affecting any other script which really on a global exports variable.

Upvotes: 1

Views: 269

Answers (1)

Tim
Tim

Reputation: 2440

It might be possible to wrap the content of those files in exactly the same pattern leading to something like

(function () {

    (function() {
      var exportObj;
      exportObj = typeof exports !== "undefined" && exports !== null ? exports : this;

      exportObj.??? = ...;

    }).call(this);

}).call(yourNamespace);

If you don't control the source, you could try to proxy it through your server and wrap it for you. You could also try to fetch the scripts as text, wrap it in the client and then insert it. Both sound kinda hacky, but are probably the easiest ways to fix the problem without being too intrusive and clever.

Upvotes: 1

Related Questions