1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I had though of using a small PHP server-side script to wrap the external files into a nicer format, but was hoping for a JS-only solution. I hadn't thought of a loading them as text via an AJAX call and wrapping them in the JS itself. I agree that it does feel kind of hacky, but I assume it would work quite well actually...
Fetching the scripts as text doesn't work - the AJAX call fails as it is cross-domain.
You can again proxy them through a small script, or use a service such as cors.io to set CORS headers for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.