可以在“标准”Apps 脚本项目中通过 eval 和 UrlFetchApp 使用 Moment.js 等外部库,因为变量 exports 和 module 未定义,因此库 installs itself into the global context
确实,我们可以通过在 Apps 脚本编辑器中检查 this 来验证结果:
代码.gs
var momentURL = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js";
function main() {
eval(UrlFetchApp.fetch(momentURL).getContentText());
Logger.log(this["moment"]);
}
执行main 产生
function e() {
return Qe.apply(null, arguments);
}
对于转译的 TypeScript,因为 exports 和 module 是全局定义的,所以 eval'd 库的初始化假定它具有比 Google Apps Script 提供的更新的运行时/包管理系统。
代码.ts
import * as moment from "moment";
const momentURL = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js";
function main() {
eval(UrlFetchApp.fetch(momentURL).getContentText());
Logger.log(`this['moment']: ${this["moment"]}`);
Logger.log(`this.module: ${this.module}`);
for (let key in this.module)
Logger.log(`this.module[${key}]: ${this.module[key]}`);
}
$ clasp push -->
代码.gs
// Compiled using ts2gas 1.6.0 (TypeScript 3.2.2)
var exports = exports || {};
var module = module || { exports: exports };
//import * as moment from "moment";
var momentURL = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js";
function main() {
eval(UrlFetchApp.fetch(momentURL).getContentText());
Logger.log("this['moment']: " + this["moment"]);
Logger.log("this.module: " + this.module);
for (var key in this.module)
Logger.log("this.module[" + key + "]: " + this.module[key]);
}
这会产生一个日志
this['moment']: undefined
this.module: [object Object]
this.module[exports]:
function e() {
return Qe.apply(null, arguments);
}
解决方案
所以eval 是成功的,但绑定到module.exports 而不是moment。您可以(在转译的 Apps 脚本中)引用 module.exports 而不是 moment:
Logger.log(module.exports().format("YYYY")); // 2019
您可能需要使用与 clasp 不同的方法,因为 ts2gas(从 v1.6.0 开始)似乎不支持 import / export transpiling。这种观察到的行为,其中 module.exports 在转译的 TS 中是 eval 的导入,看起来非常脆弱,并且在编写实际的 TypeScript 时肯定不容易解决。
相关: