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

家住魔仙堡 提交于 2020-01-02 08:05:48

问题


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?


回答1:


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.)

  • 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


来源:https://stackoverflow.com/questions/26267948/defining-globals-in-google-apps-script-that-can-be-used-across-multiple-projects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!