【问题标题】:Using transpiled ES6 in Google Apps Script => ReferenceError: "SomeClass" is not defined在 Google Apps 脚本中使用转译的 ES6 => ReferenceError: "SomeClass" is not defined
【发布时间】:2015-09-28 09:52:22
【问题描述】:

我正在尝试在 Google 电子表格(在 script.google.com 部分)中使用 ES6。我对 JavaScript 很陌生,也许这个错误是微不足道的......


  • 28/09:由于我只是使用 Google Apps 脚本库名称(记录器)而更改了帖子的错误,我切换到 SomeClass。我正在寻找模块,因为我的声明不是好的声明

我做了什么:

  • 创建了一个 webpack 项目
  • 创建了一个 Logger 类
  • 在我导入 Logger 类的地方创建了一个 main.js
  • WebPack 从我的 main.js 生成一个包
  • 我将 bundle.js 复制/粘贴到 script.google 上的捆绑文件中
  • 我尝试在 script.google 中运行测试,但得到 ReferenceError:SomeClass 未定义。`

这是我的代码:

SomeClass.js

export default class SomeClass {
    constructor() {
        this.loggerSheet = SpreadsheetApp.getActiveSpreadsheet()
                                    .getSheetByName("ImportLog");
    }

    LogInfo(data) {
      Logger.log(data);
      loggerSheet.appendRow([new Date(), "INFO", data]);
    }
}

Main.js

import SomeClass from './SomeClass.js';

在 script.google 中测试

function test_bundle() {
  var someClass = new SomeClass(); //<== breaks here
}

Bundle.js => 复制/粘贴到 script.google

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

    'use strict';

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

    var _SomeClassJs = __webpack_require__(4);

    var _SomeClassJs2 = _interopRequireDefault(_SomeClassJs);

/***/ },
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */
/***/ function(module, exports) {

    "use strict";

    Object.defineProperty(exports, "__esModule", {
        value: true
    });

    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

    var SomeClass = (function () {
        function SomeClass(option) {
            _classCallCheck(this, SomeClass);

            this.loggerSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ImportLog");
        }

        _createClass(SomeClass, [{
            key: "logInfo",
            value: function logInfo(data) {
                loggerSheet.appendRow([new Date(), "INFO", data]);
            }
        }]);

        return SomeClass;
    })();

    exports["default"] = SomeClass;
    module.exports = exports["default"];

/***/ }
/******/ ]);

【问题讨论】:

  • 我不知道转译到底是什么以及您的最终目标是什么,但 Logger 是一个保留的 Google Apps Script 类,您不能(或不应该)更改它。另外,请记住,GAS 不是您日常使用的异步/客户端 Javascript,Google 的编译器有一些您可能需要解决的更改,例如。你不能同时使用 2 个函数,没有 setTimeout 也没有 webWorkers。
  • 感谢您的信息。此处转译是为了从 ES6 代码编写 ES5 代码。
  • 你删除了我一个错误@Kriggs,因为 Google Apps 脚本中确实存在 Logger,我认为我的包导入很好。这不是因为更改名称会导致错误 bcaoming ReferenceError: "SomeClass" is not defined。所以我现在可能只需要学习如何创建一个模块。谢谢
  • 这个问题的回复可以在this post找到。

标签: javascript google-apps-script google-sheets ecmascript-6 webpack


【解决方案1】:

所以我玩这个已经有一段时间了;在 GAS 中使用转译的 ES6(甚至 ES7/next 功能)。您需要克服的主要障碍是将模块中的函数暴露给全局范围。

在浏览器中,这可能是windowdocument。在 GAS 中没有这样的全局变量。我将其标记为主要 Code.gs 中的 this 上下文。

Webpack 允许您构建独立模块来分发库等This is the link to the Webpack docs that covers changing the output module type

output: {
    libraryTarget: "this",
    path: __dirname + '/dist',
    filename: 'Code.gs'
},

这就是你的输出配置应该是什么样子的。

然后您应该从您的主 .js 文件中导出函数以将它们附加到全局上下文,如下所示:

export function onInstall(e) {
  onOpen(e);
}

从这里您应该像往常一样将脚本复制并粘贴到 GAS 脚本编辑器中,并让它运行 onInstall 函数以使其访问您的驱动器/工作表/等。

希望这会有所帮助!

【讨论】:

  • 我无法让它工作。 libraryTarget are here 的 webpack 2 文档,但它们看起来与您链接的文档几乎相同。无论如何,我无法让它工作。当我export function foo webpack 仍然将它放在一个附件中时,因此在脚本编辑器中导出的函数在顶部的下拉列表中不可用。我想有可能在解析脚本后,附件将这些函数导出到全局或this 范围,因此它们可能是可访问的。
【解决方案2】:

我尝试了上面提到的几种建议方法。但是,将这个插件与 webpack 2.X 一起使用是唯一对我有用的方法。

https://github.com/fossamagna/gas-webpack-plugin

请注意:这还不适用于 webpack 4.X。

我可以在这里反刍他们的 Readme.md,但我觉得没有必要。

简而言之,您需要将此插件添加到您的 webpack 配置中,然后将函数添加到 global。这些函数被添加为顶级函数。

【讨论】:

  • 它现在支持 Webpack 4.X :)
【解决方案3】:

2018 年更新:

如果您渴望在 GAS 中使用现代 Javascript,您可以使用 James 所描述的 Webpack,或者如果您愿意使用 Typescript,您可以使用 clasp

Clasp 是一个官方的 GAS 部署工具包,可让您在本地开发您的 Apps Script 项目,并在完成后将其部署到 Apps Script。由于代码是本地代码,因此您可以在构建 Apps Script 项目时使用自己喜欢的 IDE 和开发工具(如 git)。

【讨论】:

    【解决方案4】:

    正如我在 cmets 中所说,GAS 不是您日常使用的 Javascript,要克服该错误,您可以创建一个全局变量“SomeClass”,然后在您在主函数中声明的函数之前删除 var 关键字。这将消除此错误,但会出现另一个错误。

    你对这个 webpack 的最终目标是什么?为什么它在 GAS 中很重要?

    【讨论】:

    • 我无法使用 GAS 的常用工具(即:github、ES6)。这个想法是在外部编写代码,然后以我能找到的更简单的方式导入它。目前似乎没有 API 可以导入外部代码。所以我只是生成一个包,然后将其复制/粘贴到 GAS。
    • 问题似乎来自我的包没有暴露我的类/函数。
    • 另外,您必须全局公开您的函数。如果需要,您可以使用 IIFE,但您必须有某种方式连接到 Google API。
    • 也许可以尝试在您的main.js 文件中尝试使用import {SomeClass} from './SomeClass.js'; 而不是import SomeClass from './SomeClass.js';
    • @ThibaultDeheurles 您现在可以使用 clasp 管理 Apps Scripts 项目:developers.google.com/apps-script/guides/clasp
    【解决方案5】:

    使用new Apps Script v8 runtime,您可以通过在appsscript.json 文件中设置"runtimeVersion": "V8" 来使用现代javascript 而无需任何转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 2017-02-18
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多