在 Google Apps Script 中使用转译的 ES6 =>参考错误:“SomeClass"没有定义 [英] Using transpiled ES6 in Google Apps Script => ReferenceError: "SomeClass" is not defined

查看:19
本文介绍了在 Google Apps Script 中使用转译的 ES6 =>参考错误:“SomeClass"没有定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  • 28/09:由于我只是使用 Google Apps 脚本库名称 (Logger),帖子的错误已更改,我切换到 SomeClass.我正在寻找模块,因为我的声明不是好的
  • 28/09: The error for the post as changed as I was just using a Google Apps Script library name (Logger), I switch to SomeClass. I'm looking to module as my declaration is not the good one

我做了什么:

  • 创建了一个 webpack 项目
  • 创建了一个 Logger 类
  • 创建了一个 main.js,我在其中导入了 Logger 类
  • WebPack 从我的 main.js 生成一个包
  • 我将 bundle.js 复制/粘贴到 script.google 上的捆绑文件中
  • 我尝试在 script.google 中运行测试,但遇到 ReferenceError:SomeClass is not defined.`
  • Created a webpack project
  • Created a Logger class
  • Created a main.js where I import the Logger class
  • WebPack generate a bundle from my main.js
  • I copy/paste the bundle.js in a bundle file on script.google
  • I try to run a test in script.google but got ReferenceError:SomeClass is not define.`

这是我的代码:

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"];

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

推荐答案

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

So I've been playing with this for a while now; using transpiled ES6 (even ES7/next features) in GAS. The main hurdle you need to overcome is exposing the functions in the modules to the global scope.

在浏览器中,这可以是 windowdocument.在 GAS 中没有这样的全局.我将它标记为主 Code.gs 中的 this 上下文.

In browsers this could be window, or document. In GAS there is no such global. What I've tagged it to is the this context in the main Code.gs.

Webpack 允许您构建独立模块来分发库等.这是包含更改输出模块类型的 Webpack 文档的链接.

Webpack allows you to build stand alone modules to distribute libraries, etc. This is the link to the Webpack docs that covers changing the output module type.

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

这就是您的输出配置的样子.

This is what your output config should look like.

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

You should then export functions from your main .js file to have them attach to the global context, like so:

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

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

From here you should copy and paste the script as you normally would into the GAS Script Editor and have it run the onInstall function to give it access to your drive/sheets/etc.

希望这有帮助!

这篇关于在 Google Apps Script 中使用转译的 ES6 =>参考错误:“SomeClass"没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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