エクスポートしたい(module.exports
)
1// Node環境用のエクスポート(GAS環境では無視される)
2if (typeof module !== 'undefined' && module.exports) {
3 module.exports = {
4 ModuleName,
5 anotherModuleName,
6 someFunction,
7 };
8}
9// GAS環境用のエクスポート(Node環境では無視される)
10else {
11 this.ModuleName = ModuleName;
12 this.anotherModuleName = anotherModuleName;
13 this.someFunction = someFunction;
14}
module.exports
の有無を確認することで、
Node環境かGAS環境かを区別できます。
GASにはエクスポート機能がないため、 すべてをグローバルの下にぶら下げる必要があります。
インポートしたい
1function importClassName() {
2 // ClassName が定義されている場合
3 if (typeof ClassName !== 'undefined') {
4 return new ClassName();
5 }
6
7 // ライブラリで定義されている場合
8 if (typeof LibraryName !== 'undefined' && LibraryName.ClassName) {
9 return new LibraryName.ClassName();
10 }
11
12 // requireが使える場合(=Node環境)
13 if (typeof require === 'function') {
14 try {
15 const { ClassName } = require('./ModuleName');
16 return new ClassName();
17 } catch (e) {
18 throw new Error(`ClassName not available via require()`);
19 }
20 }
21 throw new Error(`ClassName is not available in this environment`);
22}
GASにはインポート機能もありません。 グローバルに定義されたモジュール名(クラス名)の有無を確認し、 必要なところでインスタンスを作成しています。
1// 別のGASの先頭で読み込む
2const _cn = importClassName();
3_cn.someFunction(...);
別のGASの先頭で、上記のように読み込むことで、 モジュールにアクセスできるようになります。