Convert Library to JavaScript closure

- 1 answer

Ad

I have an external library of JavaScript functions that I need to pull into my server-side Google Apps Script project. I'm doing this mainly for performance reasons, but also because Google now recommends against using external libs.

In the current configuration, functions in the external library are referenced by <Libname>.funcName(), and any globals in the library are likewise contained, e.g. <Libname>.globA. If I just copy the library into a file in my project, those functions (and "globals") would be referenced as funcName() alone. I've got hundreds of such references in my project that potentially need to change. That's fine; it's something a global search & replace can address. However, I have worries about "namespace" problems... Since the library is third-party code, I've had no control over it, and now I'm running into name collisions, as objects and functions in the library have the same names as some of my code.

How can I pull this code into my project in a way that will keep its internal details separate from my code? Is there a way to do that and retain the current naming convention, <Libname>.funcName()? I believe that JavaScript closures are the right solution, but don't know enough about them.

My project, Code.gs

var globA = { key: 'aKey', value: 'valA' };

function myFunction() {
  var a = MyLib.getValue();
  Logger.log( JSON.stringify( a ) );  // { key: 'libKey', value: 'valLibA' };
}

function getValue() {
  return globA;
}

Library "MyLib", Code.gs

var globA = { key: 'libKey', value: 'valLibA' };

function getValue(  ) {
  return globA;  
}
Ad

Answer

Ad

There are two ways to solve this.

You could use browserify to convert a node library into a piece of code that can simply be pasted into the apps script editor.

Or you wrap the code yourself using an immediately invoked function expression.

Like this:

var MyLib = (function() {
  var globA = { key: 'libKey', value: 'valLibA' };
  function getValue(  ) {
    return globA;  
  }

  return {
    globA: globA,
    getValue: getValue
  }
})();

btw. if you create several .gs files, the code/definitions in them will be executed in the order the file names are displayed on the left side of the editor.

Ad
source: stackoverflow.com
Ad