在已编译的Apps脚本中导入moment.js

问题描述 投票:0回答:1

我有必要在本地开发的Apps Script项目中使用moment.js,该项目使用google\clasp从TypeScript转换。

我已经尝试在项目中添加js库,正如我在.gs中正常编写时那样,但是使用clasp似乎不允许我使用这种方式。

我已经尝试过,正如我在其他Stack Overflow答案中读到的那样,使用eval这样没有成功:

eval(UrlFetchApp.fetch('library.min.js url').getContentText());

在所有情况下,在我推送到Apps脚本并在Apps脚本编辑器中运行该功能后,我收到了

ReferenceError:未定义“时刻”。 (第6行,文件“测试”)

我的TS文件:enter image description here

typescript google-apps-script clasp
1个回答
1
投票

可以在“标准”Apps脚本项目中通过evalUrlFetchApp使用Moment.js等外部库,因为变量exportsmodule未定义,因此库installs itself into the global context

实际上,我们可以通过在Apps脚本编辑器中检查this来验证结果:

Code.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,因为exportsmodule是全局定义的,所以eval库的初始化假设它具有比Google Apps脚本提供的更新的运行时/包管理系统。

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

Code.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。您可以(在已编译的应用程序脚本中)引用module.exports而不是moment

Logger.log(module.exports().format("YYYY")); // 2019

可能你需要使用与clasp不同的方法,因为看起来ts2gas(从v1.6.0开始)不支持import / export transpiling。这种观察到的行为,其中module.exports在转换TS中是eval'd导入似乎非常脆弱,并且在编写实际的TypeScript时肯定不容易解决。

有关:

© www.soinside.com 2019 - 2024. All rights reserved.