javascriptgoogle-apps-scriptmodulemaintainabilitygoogle-apps-script-addon

How to reuse a single JavaScript in both server and client components of G Suite Add-on?


I have a JavaScript file that's a generated parser (let's call it MyParser), which I am using in an add-on for Google Forms.

It needs to be used in the client side's Sidebar.html where I'm including it with HtmlService.createHtmlOutputFromFile('MyParser.js').getContent();, which means it must be an .html file as far as I understand. Then it must be used on the server side where I have it in a file MyParser.js.gs.

With my current solution, it's duplicated in my file structure:

Code.gs
MyParser.js.gs
MyParser.js.html
Sidebar.html

Is there a way I can make this work without having two files? Edit: As I understand it, libraries are only for the server side.

If not, any hints to making the updating of the two files more robust (currently it's manual copy/paste)?

Edit: According to the best practices, one must wrap the JavaScript inside a <script> tag inside the .html file:

Notice that the included files contain <style> and <script> tags because they're HTML snippets and not pure .css or .js files.

So it seems it's not easy to have just one file.


Solution

  • As far as I could tell, there's no way to reuse a single file and respect Google's best practices.

    My solution, following @tehhowch's advice, was with @google/clasp and doing local development.

    To build the parser (in another GitHub project), I use npm-run-script. So, I just appended a && bash makeHTML.sh to the build script.

    Inside makeHTML.sh I wrapped the built MyParser.js file in a <script> tag with:

    #!/usr/bin/env bash
    { echo "<script>"; cat MyParser.js; echo "</script>"; } > MyParser.js.html
    

    Since I'm using bash it's not a true node.js solution (won't run unless there's bash installed). If someone knows of a better way to pull off the wrapping that's 100% node and doesn't require installing a whole bunch of other modules, feel free to edit the answer.