Reputation: 45730
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.
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;
}
Code.gs
var globA = { key: 'libKey', value: 'valLibA' };
function getValue( ) {
return globA;
}
Upvotes: 3
Views: 202
Reputation: 8139
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.
Upvotes: 2
Reputation: 1010
The best way to structure your modules while keeping some level of closure is in my opinion to use Asynchronous Module Definition (AMD). A good library to do that would be requirejs.
You will define and require your modules like so :
define(['path/to/your1stLib', 'path/to/your2ndLib', ...], function(Your1stLib, Your2ndLib, ...) {
var MyOtherLib = {
Your1stLib.doStuff(...)
// rest of the code
}
return MyOtherLib;
});
Upvotes: 0
Reputation: 4045
I would suggest wrapping the library as an AMD module and use requirejs or similar to load dependencies.
Upvotes: 0