简体   繁体   English

在Google Apps脚本中定义可在多个项目中使用的全局变量

[英]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. 我有大约15-20个Google Apps脚本项目,它们都使用相同的全局变量列表。

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? 有没有人使用库来跨项目定义全局变量?

Using a library for shared constants is the most effective way to share constant objects between Google Apps Scripts. 使用共享常量库是在Google Apps脚本之间共享常量对象的最有效方法。 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. 使用ConstLib的所有脚本都需要在“开发模式”为ON的情况下执行此操作,否则您仍需要手动更新每个脚本。 (Risk: save a buggy version of ConstLib and all your scripts will immediately break.) (风险:保存错误版本的ConstLib,所有脚本都会立即中断。) 截图
  • The constants are attributes of the library, so will need to be referenced using the library name, eg 常量是库的属性,因此需要使用库名称来引用,例如

     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. 在现有脚本中,您可能会发现将现有常量块更改为对ConstLib的引用很方便,因此您无需触及其余代码。 eg 例如

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

Example

ConstLib ConstLib

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

Use Constlib 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM