Using transpiled ES6 in Google Apps Script => ReferenceError: “SomeClass” is not defined

前端 未结 5 1360
生来不讨喜
生来不讨喜 2020-12-17 00:29

I\'m trying to use ES6 in a Google Spreadsheet (in the script.google.com part). I\'m pretty new to JavaScript and maybe the error is trivial ...


5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 00:40

    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.

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

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

    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.

    Hope this helps!

提交回复
热议问题