在Google Apps脚本中定义可在多个项目中使用的全局变量 [英] Defining globals in Google Apps Script that can be used across multiple projects

查看:95
本文介绍了在Google Apps脚本中定义可在多个项目中使用的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大约有15-20个Google Apps脚本项目,它们都使用相同的全局变量列表.

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?

推荐答案

使用共享常量库是在Google Apps脚本之间共享常量对象的最有效方法.一些警告:

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

  • 所有使用ConstLib的脚本都需要在开发模式"为ON的情况下进行操作,否则,您仍然需要手动更新每个脚本. (风险:保存错误版本的ConstLib,您的所有脚本都将立即中断.)
  • 常量是库的属性,因此需要使用库名进行引用,例如

  • 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 );

在您现有的脚本中,您可能会发现将现有常量块更改为对ConstLib的引用很方便,因此您无需触摸其余代码.例如

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

ConstLib

ConstLib

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

使用Constlib

Use Constlib

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

记录输出

[14-10-09 14:51:47:258 EDT] Red
[14-10-09 14:51:47:259 EDT] Blue

这篇关于在Google Apps脚本中定义可在多个项目中使用的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆