7

Is there a way to move some functions into separate files in google app script? currently my Code.gs looks like the following:

function onSubmit(e) {}

function readSpreadsheet(sheet) {}
function writeSpreadsheet(sheet, data) {}

function sendEmail() {}

function helperLogic1() {}
function helperLogic2() {}
function helperLogic3() {}
function helperLogic4() {}

So to make my code looks nicer ;p .. I want to move functions related to spreadsheet to spreadsheet.gs email to email.gs etc. So after moving them, how do I load it from the code.gs?

Thanks

1 Answer 1

10

You can move any function to any script file inside the same project without restriction, it is indeed easier to read when you split the code in different categories when the code is long.

When you execute any of these function it behaves as if all of them where in the same .gs file. The project is the real container, not the file.

Sign up to request clarification or add additional context in comments.

4 Comments

It works as you said. Thanks alot. But then is there any order as to how the script is loaded. I mean if I accidentally write the same function in two files, what would happen?
in case 2 functions have the same name I'm not sure one can know for sure which one will be executed first...I would bed that the script is read in the order you typed it but that's a pure guess ! Honestly I never tried (and never had this kind of accident ;-)
I can confirm. While all the files are loaded, load order is arbitrary and properly somehow related to times when they were created on google cloud infrastructure. I have git cloned project and then pushed it to app script, in one case it works just fine, in another case it throws error that there uninitialised variable. Closures are your friends.
I noticed, that functions or variables moved to other file (js or gs) aren't accesible when script run. Only later, f.e, when triggered by button or smth. There is an error that says: <this function/variable> is not defined...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.