'How to include a file into your project
I'm creating a Google Apps Script that's kind of a quiz marker / email merger in one. I've got everything working but my code is pretty long because I find myself having to use procedural coding. This is mostly because I don't know how to use the editor to include a class / library.
I've viewed the Crash Course Video by Kalyan on using the Script Editor, but it didn't answer my question. I've also scoured the internet with no luck.
If you look in the top left of this screenshot, you'll see I have Code.gs and test.gs:

I have all my code in the Code.gs file, but I want to include test.gs in Code.gs. Once I figure out how to do that, I'd like to create a couple of simple classes to organize my functions a bit better (and possibly re-use my classes later).
Thanks in advance!
Solution 1:[1]
To clarify Zig Mandel's answer and add to it:
All .gs files that are located in the same Script Project have global access to each other. That is to say that a function that you define in test.gs is accessible by Code.gs if they are in the same Script Project
You can create your own library of code. To do this you would simply create another Script Project, then go to
Resources -> Manage libraries..., and add the project key of your original project (that contains the Code.gs and test.gs files). The project key is located inFile -> Project properties.
The second bullet point is a good way to organize your code. If you have the same code that you are reusing throughout many Script Projects, then you want to put those functions into one Script Project and create a library out of them, as I explained above.
Solution 2:[2]
You already included the code. Should work as is. You can also look at the apps script docummentation and learn to use libraries for code reuse: https://developers.google.com/apps-script/guide_libraries.
This makes development easier but for best performance you should include them all in your project before publishing like you did this time.
Solution 3:[3]
Part of the problem may be the order of execution. The .gs files are executed in order of creation. Copying Code.gs, deleting the original, then running functions from the new copy may fix your problem.
Solution 4:[4]
<?!= include('JavaScript.html'); ?>
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris Cirefice |
| Solution 2 | |
| Solution 3 | Janine White |
| Solution 4 |
