How to Create One Library in Google App Script and Import It Into Many SpreadSheets

I the need to run a single script on and number of spreadsheets within a single Google Drive and I don’t want to copypaste the code each time I create a new one. What the script is expected to do is, simply, o take any field starting with FRR- (Jira Project ID, e.g. FRR-8081 ) and prepend the Jira URL so that automatically I'll end up with a clickable link to the Jira card.

Pavol Kutaj
2 min readJun 20, 2023
BEFORE: FRR-8081
AFTER: https://pavol.atlassian.net/browse/FRR-8081

So, I want to write a self-standing script file and import it via three lines of code, the say as I’d import a Python module simply with 🠋

import <module>
<module>.<function_call()>

Create a standalone script, get its ID and import it via a dedicated GUI feature. There is no import keyword in GAS.

  • Create a standalone script by going to your Google Drive, clicking on the “New” button, selecting “More” and then selecting “Google Apps Script”.
  • There is no direct way — i.e. import / require — statement to import an existing standalone script file into a container-bound script within a Google Sheet.
  • Still, you can run a standalone script from within a Google Sheet without copying the code by publishing the standalone script as a library.
  • If you have included a library in your container-bound script within a Google Sheet and want to run a function from the library when the sheet is opened, you can do so for example by using one of the built-in simple triggers (onOpen(), onEdit() or onSelectionChange())
  • Here’s the “Library” code in a standalone jiraHandlers file
// jiraHandlers
function makeJiraLink() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getActiveRange();
var row = range.getRow();
var col = range.getColumn();
var cell = sheet.getRange(row, col);
var value = cell.getValue().toString(); // Convert value to a string
var url = 'https://pavol.atlassian.net/browse/' + value;
if (value.startsWith('FRR-')) {
cell.setFormula('=HYPERLINK("' + url + '","' + value + '")');
}
}
  • go to project settings ⟹ IDs ⟹ Copy the Script ID (it’s part of the URL, too)
1kDD-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-wmOrnbn
  • in any container-bound script go to App Scripts ⟹ Library ⟹ + ⟹ Paste the Script ID
  • within the editor write simply (if you want onEdit() trigger)
function onEdit() {
//<library_name>.<function_call>
jiraHandlers.makeJiraLink()
}

⟹ DONE; the URLs are created in each new sheet containing bunch of jira card IDs after adding of the code snippet 🠉

--

--

No responses yet