21

I am trying to organize my code for a Spreadsheet in several script files. Within the script editor I can create as many *.gs files as I want, but I can't figure out how to access code that would be defined in another script.

Simple Example of what I'd like do achieve:

Code.gs:

function onEdit(){
   myFunctionFromLibrary_gs();
} 

Library.gs:

function myFunctionFromLibrary_gs(){
   Browser.msgBox("hi there");
}

The onEdit() is obviously called by a Trigger. Without modification this will result in a Runtime-Error, stating that

myFunctionFromLibrary_gs TypeError: is not a function, it is undefined.

So how can I make this work, or is this currently not supported?

Thx in advance for your help.

apadana
  • 13,456
  • 15
  • 82
  • 98
leostone
  • 415
  • 1
  • 5
  • 9

3 Answers3

25

Yes, it's possible.

  1. You are not limited to a single server Code.gs file. You can spread server code across multiple files for ease of development. All of the server files are loaded into the same global namespace, so use JavaScript classes when you want to provide safe encapsulation.

Reference: Google Documentation - features and limitations

gihanchanuka
  • 4,783
  • 2
  • 32
  • 32
  • 1
    The context-menu action "Go to definition" doesn't seem to work across files, making it difficult to navigate large projects broken up this way. The only way to find a method would be to open every file in order and search for it ctrl-f. – Carl G Mar 04 '22 at 16:38
14

I don't know what the _gs suffix means for Google, but without it (see code bellow), the code works.

file1.gs:

function onEdit(){
   myFunctionFromLibrary();
}

file2.gs

function myFunctionFromLibrary(){
   Browser.msgBox("hi there");
}
megabyte1024
  • 8,482
  • 4
  • 30
  • 44
  • hm, actually the "_gs" was just for illustration purpose, it's not in the actual code. but thx, that means it should be working, i will investigate further – leostone Jul 30 '12 at 16:54
  • @user1563470. I tried the code both with "_gs" suffix and without it. In the 1st case there is the same error as in your original post. In the 2nd case everything works without any error. – megabyte1024 Jul 30 '12 at 16:59
  • it's working now , i can't say why it wasn't previously, confused ... BUT THANX – leostone Jul 30 '12 at 17:22
6

I know this is an old question but I found it looking for a similar task and happened to find the answer during my same search. From the docs at https://developers.google.com/apps-script/guide_libraries#writingLibrary:

If you want one or more methods of your script to not be visible (nor usable) to your library users, you can end the name of the method with an underscore. For example, myPrivateMethod_().

While your function does not END in an underscore, it may have special meaning in other places than just this, or the _gs suffix may also have special meaning (particularly given the same filename suffix).

btharper
  • 116
  • 1
  • 4