Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining globals in Google Apps Script that can be used across multiple projects

I have about 15-20 Google Apps Script projects which all use the same list of global variables.

What I've done is defined all of the globals at the top of the first script file in the project, and then copied and pasted the block of code to the same spot in each project. So if I make a change in one, I copy and paste the entire thing from that one to the rest of them. It gets time-consuming.

Is there a better way to do this? Is it using Libraries? Does anyone use Libraries for defining globals across projects?

like image 218
Employee Avatar asked Feb 11 '23 20:02

Employee


1 Answers

Using a library for shared constants is the most effective way to share constant objects between Google Apps Scripts. Some caveats:

  • All scripts using the ConstLib will need to do so with "Development Mode" ON, otherwise you'll still need to update each of them manually. (Risk: save a buggy version of ConstLib and all your scripts will immediately break.) screenshot
  • The constants are attributes of the library, so will need to be referenced using the library name, e.g.

    var log = SpreadsheetApp.openById( ConstLib.auditLogId );
    

    In your existing scripts, you may find it convenient to change your block of existing constants into references to the ConstLib, so you won't need to touch the remaining code. e.g.

    var auditLogId = ConstLib.auditLogId;
       . . .
    var log = SpreadsheetApp.openById( auditLogId );
    

Example

ConstLib

var roses = "Red", violets = "Blue";

Use Constlib

function myFunction() {
  Logger.log(ConstLib.roses);
  Logger.log(ConstLib.violets);
}

Logging Output

[14-10-09 14:51:47:258 EDT] Red
[14-10-09 14:51:47:259 EDT] Blue
like image 54
Mogsdad Avatar answered Feb 14 '23 08:02

Mogsdad