Hi. 🙂
I experienced this in my Google Apps Script project. I thought each .gs
file was isolated, nope.
It's like embedding multiple .js
files in an HTML
. All script files are loaded into the same global context, as if they're one continuous script.
For example, we have many .js
files (without using type="module"
) in the HTML
.
Each script has this similarly named functions:
First script.
For instance, it is defined in <script src="./js/firstScript.js"></script>
:
Then in the other script.
Defined in <script src="./js/secondScript.js"></script>
:
Then calling that init
function somewhere from another script file.
Let's say from <script src="./js/main.js"></script>
:
Depends on the order of the scripts stacking, we would see either the first script log or the second one. But not both.
We would find no error because JavaScript allows overwriting function
(and var
). But not for the let
and const
.
Meaning, if we define multiple functions with the same name, the last one wins.
The linter wouldn't recognise the "bug" we made in this multi-file shenanigans.
Back to Apps Script. In that project, I have multiple .gs
files. They are all referencing one Google Sheets for the data. Then I generate the PDF files based on that data, through multiple Google Docs templates. The Apps Script is there to orchestrate the flow.
The orchestration goes as such:
The folders are in Google Drive, within the parent folder where the Sheets and Docs files reside.
Multiple .gs Files, One Project
In Apps Script, adding multiple .gs
files does not create isolated modules. All functions live in the global scope, regardless of which file they're written in.
In other words: Apps Script doesn't care if your function is in main.gs
or report.gs
‐ if two functions share the same name, they will collide.
Function Overwriting without Warning
If you define function generateReport()
in reportSalesDivision.gs
, then again in reportITDivision.gs
, only one will run — usually the last one loaded.
You won't get an error. You'll get silent overwriting. Debugging becomes a bloody mess.
In my experience, I realised it after two hours bantering with ChatGPT 4o (and o3 for a bit). Both had no overall context, only my snippets. 4o suggested this and that like a proper maniac — none worked. Model o3 was baffled, I halted its analysis. 🤣 I even muttered about Google's backend since the error messages were inconsistent. 🤦
Then, the "oh" moment. 💥
I switched between files in my code editor. Oh!, I said. Oh, every file has one similar function name! Well I never. 🤣
Unique Function Naming
If you must reuse logic, define shared helpers (with unique names) in a dedicated utils.gs
file for instance.
That's about it. I hope this is interesting. Refactor gently. 👍
Comments
Post a Comment