如何从另一个应用程序引用一个应用程序脚本文件

发布于 2025-02-12 08:26:04 字数 734 浏览 2 评论 0原文

我的应用程序脚本项目中有多个文件。其中一些是为较大应用提供实用程序功能的库文件。如何将它们导入我的主文件?

例如,在节点中,我将能够导入update-cell-1.gsupdate-cell-2.gs /code>这样的文件:

// update-cell-1.gs
export default function() {
   // code to update cell 1
}

// update-cell-2.gs
export default function() {
   // code to udpate cell 2
}

// main.gs
import updateCell1 from "update-cell-1.gs";
import updateCell2 from "update-cell-2.gs";

function main() {
  updateCell1();
  updateCell2();
}

main();

应用程序脚本中的等效内容是什么?

当我尝试使用模块。Exports时,我会收到此错误:

ReferenceError: module is not defined

当我尝试使用导出默认时,我会得到此错误:

SyntaxError: Unexpected token 'export'

I have multiple files in my apps script project. Some of them are library files that provide utility functions for a larger app. How can I import them into my main file?

For example, in Node, I would be able to import update-cell-1.gs and update-cell-2.gs into my main.gs file like this:

// update-cell-1.gs
export default function() {
   // code to update cell 1
}

// update-cell-2.gs
export default function() {
   // code to udpate cell 2
}

// main.gs
import updateCell1 from "update-cell-1.gs";
import updateCell2 from "update-cell-2.gs";

function main() {
  updateCell1();
  updateCell2();
}

main();

What is the equivalent in apps script?

When I try using module.exports, I get this error:

ReferenceError: module is not defined

When I try using export default, I get this error:

SyntaxError: Unexpected token 'export'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

成熟稳重的好男人 2025-02-19 08:26:04

与< node.js 或JS Web Frameworks,您可以在任何文件中调用任何文件直接无需导出或导入任何内容的同一脚本项目。

Unlike or js web frameworks, You can call any function in any file in the same script project directly without exporting or importing anything.

独自←快乐 2025-02-19 08:26:04

这是一个脚本,可以支持脚本项目中的所有文件。

您可以选择单独的文件或所有一个JSON文件。您还可以选择要保存的文件。

GS:

function saveScriptBackupsDialog() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('backupscripts1'), 'Script Files Backup Dialog');
}

function scriptFilesBackup(obj) {
  console.log(JSON.stringify(obj));
  const scriptId = obj.script.trim();
  const folderId = obj.folder.trim();
  const saveJson = obj.saveJson;
  const saveFiles = obj.saveFiles;
  const fA = obj.selected;
 
  if (scriptId && folderId) {
    const base = "https://script.googleapis.com/v1/projects/"
    const url1 = base + scriptId + "/content";
    const url2 = base + scriptId;
    const options = { "method": "get", "muteHttpExceptions": true, "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
    const res1 = UrlFetchApp.fetch(url1, options);
    const data1 = JSON.parse(res1.getContentText());
    const files = data1.files;
    const folder = DriveApp.getFolderById(folderId);

    const res2 = UrlFetchApp.fetch(url2, options);
    const data2 = JSON.parse(res2.getContentText());
    let dts = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyyMMdd-HH:mm:ss");
    let subFolderName = Utilities.formatString('%s-%s', data2.title, dts);
    let subFolder = folder.createFolder(subFolderName);
    if (saveFiles) {
      files.forEach(file => {
        if (file.source && file.name) {
          let ext = (file.type == "HTML") ? ".html" : ".gs";
          if (~fA.indexOf(file.name)) {
            subFolder.createFile(file.name + ext, file.source, MimeType.PLAIN_TEXT)
          }
        }
      });
    }
    if (saveJson) {
      subFolder.createFile(subFolderName + '_JSON', res1, MimeType.PLAIN_TEXT)
    }
  }
  return { "message": "Process Complete" };
}

function getAllFileNames(fObj) {
  if (fObj.scriptId) {
    const base = "https://script.googleapis.com/v1/projects/"
    const url1 = base + fObj.scriptId + "/content";
    const options = { "method": "get", "muteHttpExceptions": true, "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
    const r = UrlFetchApp.fetch(url1, options);
    const data = JSON.parse(r.getContentText());
    const files = data.files;
    const names = files.map(file => file.name);
    return names;
  }

}

HTML:

<!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <style>
        input {margin: 2px 5px 2px 0;}
    #btn3,#btn4{display:none}
    </style>
</head>

<body>
    <form>
        <input type="text" id="scr" name="script" size="60" placeholder="Enter Apps Script Id" onchange="getFileNames();" />
        <br /><input type="text" id="fldr" name="folder" size="60" placeholder="Enter Backup Folder Id" />
        <div id="shts"></div>
    <br /><input type="button" value="0" onClick="unCheckAll();" size="15" id="btn3" />
    <input type="button" value="1" onClick="checkAll();"size="15" id="btn4"/>
        <br /><input type="checkbox" id="files" name="saveFiles" checked /><label for="files">Save Files</label>
        <br /><input type="checkbox" id="json" name="saveJson" checked /><label for="json">Save JSON</label>
        <br /><input type="button" value="Submit" onClick="backupFiles();" />
    </form>
        <script>
      function getFileNames() {
        const scriptid = document.getElementById("scr").value;
        google.script.run
        .withSuccessHandler((names) => {
          document.getElementById('btn3').style.display = "inline";
          document.getElementById('btn4').style.display = "inline";
          names.forEach((name,i) => {
           let br = document.createElement("br"); 
           let cb = document.createElement("input");
           cb.type = "checkbox";
           cb.id = `cb${i}`;
           cb.name = `cb${i}`;
           cb.className = "cbx";
           cb.value = `${name}`;
           cb.checked = true;
           let lbl = document.createElement("label");
           lbl.htmlFor = `cb${i}`;
           lbl.appendChild(document.createTextNode(`${name}`));
           document.getElementById("shts").appendChild(cb);
           document.getElementById("shts").appendChild(lbl);
           document.getElementById("shts").appendChild(br);
          });
        })
        .getAllFileNames({scriptId:scriptid}); 
      }
      function unCheckAll() {
        let btns = document.getElementsByClassName("cbx");
        console.log(btns.length);
        for(let i =0;i<btns.length;i++) {
          btns[i].checked = false;
        }
      }
      function checkAll() {
        let btns = document.getElementsByClassName("cbx");
        console.log(btns.length)
        for(let i = 0;i<btns.length;i++) {
          btns[i].checked = true; 
        }
      }
      function backupFiles() {
        console.log('backupFiles');
        sObj = {};
        sObj.script = document.getElementById('scr').value;
        sObj.folder = document.getElementById('fldr').value;
        sObj.saveJson = document.getElementById('json').checked?'on':'';
        sObj.saveFiles = document.getElementById('files').checked?'on':'';
        sObj.selected = [];
        console.log("1");
        const cbs = document.getElementsByClassName("cbx");
        let selected = [];
        for(let i = 0;i<cbs.length; i++) {
          let cb = cbs[i];
          if(cb.checked) {
            sObj.selected.push(cb.value)
          } 
        }
        console.log("2");
        google.script.run
        .withSuccessHandler(function(obj){google.script.host.close();})
        .scriptFilesBackup(sObj);
        console.log(JSON.stringify(sObj));
      }
        </script>
</body>

</html>

我想念的一些辅助功能也许让我知道。我一直使用此时间备份我的代码。

典型的后备看起来像这样:

”在此处输入图像说明”

Here's a script that backs up all of the files in a script project.

You can choose either separate files or all one JSON file. You can also select which files that you wish to save.

GS:

function saveScriptBackupsDialog() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('backupscripts1'), 'Script Files Backup Dialog');
}

function scriptFilesBackup(obj) {
  console.log(JSON.stringify(obj));
  const scriptId = obj.script.trim();
  const folderId = obj.folder.trim();
  const saveJson = obj.saveJson;
  const saveFiles = obj.saveFiles;
  const fA = obj.selected;
 
  if (scriptId && folderId) {
    const base = "https://script.googleapis.com/v1/projects/"
    const url1 = base + scriptId + "/content";
    const url2 = base + scriptId;
    const options = { "method": "get", "muteHttpExceptions": true, "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
    const res1 = UrlFetchApp.fetch(url1, options);
    const data1 = JSON.parse(res1.getContentText());
    const files = data1.files;
    const folder = DriveApp.getFolderById(folderId);

    const res2 = UrlFetchApp.fetch(url2, options);
    const data2 = JSON.parse(res2.getContentText());
    let dts = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyyMMdd-HH:mm:ss");
    let subFolderName = Utilities.formatString('%s-%s', data2.title, dts);
    let subFolder = folder.createFolder(subFolderName);
    if (saveFiles) {
      files.forEach(file => {
        if (file.source && file.name) {
          let ext = (file.type == "HTML") ? ".html" : ".gs";
          if (~fA.indexOf(file.name)) {
            subFolder.createFile(file.name + ext, file.source, MimeType.PLAIN_TEXT)
          }
        }
      });
    }
    if (saveJson) {
      subFolder.createFile(subFolderName + '_JSON', res1, MimeType.PLAIN_TEXT)
    }
  }
  return { "message": "Process Complete" };
}

function getAllFileNames(fObj) {
  if (fObj.scriptId) {
    const base = "https://script.googleapis.com/v1/projects/"
    const url1 = base + fObj.scriptId + "/content";
    const options = { "method": "get", "muteHttpExceptions": true, "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
    const r = UrlFetchApp.fetch(url1, options);
    const data = JSON.parse(r.getContentText());
    const files = data.files;
    const names = files.map(file => file.name);
    return names;
  }

}

html:

<!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <style>
        input {margin: 2px 5px 2px 0;}
    #btn3,#btn4{display:none}
    </style>
</head>

<body>
    <form>
        <input type="text" id="scr" name="script" size="60" placeholder="Enter Apps Script Id" onchange="getFileNames();" />
        <br /><input type="text" id="fldr" name="folder" size="60" placeholder="Enter Backup Folder Id" />
        <div id="shts"></div>
    <br /><input type="button" value="0" onClick="unCheckAll();" size="15" id="btn3" />
    <input type="button" value="1" onClick="checkAll();"size="15" id="btn4"/>
        <br /><input type="checkbox" id="files" name="saveFiles" checked /><label for="files">Save Files</label>
        <br /><input type="checkbox" id="json" name="saveJson" checked /><label for="json">Save JSON</label>
        <br /><input type="button" value="Submit" onClick="backupFiles();" />
    </form>
        <script>
      function getFileNames() {
        const scriptid = document.getElementById("scr").value;
        google.script.run
        .withSuccessHandler((names) => {
          document.getElementById('btn3').style.display = "inline";
          document.getElementById('btn4').style.display = "inline";
          names.forEach((name,i) => {
           let br = document.createElement("br"); 
           let cb = document.createElement("input");
           cb.type = "checkbox";
           cb.id = `cb${i}`;
           cb.name = `cb${i}`;
           cb.className = "cbx";
           cb.value = `${name}`;
           cb.checked = true;
           let lbl = document.createElement("label");
           lbl.htmlFor = `cb${i}`;
           lbl.appendChild(document.createTextNode(`${name}`));
           document.getElementById("shts").appendChild(cb);
           document.getElementById("shts").appendChild(lbl);
           document.getElementById("shts").appendChild(br);
          });
        })
        .getAllFileNames({scriptId:scriptid}); 
      }
      function unCheckAll() {
        let btns = document.getElementsByClassName("cbx");
        console.log(btns.length);
        for(let i =0;i<btns.length;i++) {
          btns[i].checked = false;
        }
      }
      function checkAll() {
        let btns = document.getElementsByClassName("cbx");
        console.log(btns.length)
        for(let i = 0;i<btns.length;i++) {
          btns[i].checked = true; 
        }
      }
      function backupFiles() {
        console.log('backupFiles');
        sObj = {};
        sObj.script = document.getElementById('scr').value;
        sObj.folder = document.getElementById('fldr').value;
        sObj.saveJson = document.getElementById('json').checked?'on':'';
        sObj.saveFiles = document.getElementById('files').checked?'on':'';
        sObj.selected = [];
        console.log("1");
        const cbs = document.getElementsByClassName("cbx");
        let selected = [];
        for(let i = 0;i<cbs.length; i++) {
          let cb = cbs[i];
          if(cb.checked) {
            sObj.selected.push(cb.value)
          } 
        }
        console.log("2");
        google.script.run
        .withSuccessHandler(function(obj){google.script.host.close();})
        .scriptFilesBackup(sObj);
        console.log(JSON.stringify(sObj));
      }
        </script>
</body>

</html>

There maybe some helper functions that I'm missing let me know. I use this all of the time to backup my code.

A typical back up looks like this:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文