Organizing Spreadsheet Code in several *.gs files

2019-04-06 20:49发布

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.

3条回答
在下西门庆
2楼-- · 2019-04-06 20:59

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

查看更多
Bombasti
3楼-- · 2019-04-06 21:04

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).

查看更多
淡お忘
4楼-- · 2019-04-06 21:19

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");
}
查看更多
登录 后发表回答