はじめに
Google Apps ScriptにはWebAppsという機能があり、簡易なWebアプリを構築し、配布する事が出来ます。例えば個人的に開発したWebアプリを少し無料でお試し公開したい、社内で業務改善ツールとして使ってもらいたい、そんな時に活躍します。この記事ではそんなGoogle Apps ScriptをスムーズにReactで構築出来るボイラープレートを作りましたので、是非使って頂ければと思い、以下に説明を記載します。
テンプレートの画面イメージ
利用するライブラリ
以下の通りとなります。ローカルからGoogle Apps Scriptを更新する為に clasp というツールを利用します。また、通常のWebサーバーへの構築と異なり、素のJavascriptをアップロードする事が出来ない為、Webpackのプラグインを追加しています。
※ Webpackのバージョンが古いものを利用しているのは、利用したいプラグインhtml-webpack-inline-source-plugin
の更新が随分前からされなくなっている為で、最新のWebpack環境で使う方法を私は見つけられませんでした。
{
"dependencies": {
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@mui/icons-material": "^5.8.4",
"@mui/material": "^5.8.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"recoil": "^0.7.4",
"typescript": "4.4.4"
},
"devDependencies": {
"@google/clasp": "^2.4.1",
"@types/google-apps-script": "^1.0.49",
"@types/node": "^16.7.13",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@types/webpack": "^5.28.0",
"html-webpack-inline-source-plugin": "1.0.0-beta.2",
"html-webpack-plugin": "4.2.0",
"ts-loader": "6.2.2",
"webpack": "4.42.1",
"webpack-cli": "3.3.11",
"webpack-dev-server": "3.10.3"
}
}
使い方
初期設定
本レポジトリをローカルに取得し、依存モジュールをインストールして下さい。
git clone https://github.com/ymuichiro/react-gas-boilerplate.git
yarn install
ローカルからGoogle Apps script側を操作する為、最初にログインを行う必要があります。
yarn run init
ソースファイルのアップロード先を指定します。.clasp.json
を開き、scriptId
にアップロード先となるスクリプトファイルのIDを入力して下さい。
{
"scriptId": "******************",
"rootDir": "./server"
}
スクリプトファイルのIDはURLの以下****の箇所となります。
https://script.google.com/home/projects/****/edit
問題なく構築が出来たか確認します。
yarn run build
処理が完了したらエディタの画面より新規Web Appsをデプロイして下さい
UIの確認を行うとき
以下を実行し、dev-serverを起動します
yarn run start
ReactからApp Scriptを呼ぶ時
src/functions/hello.ts
に以下のようなスクリプトがあります。
export async function callhello() {
return new Promise((resolve, reject) => {
google.script.run
.withSuccessHandler((result: string) => {
alert(result);
})
.withFailureHandler(() => {
alert('error at withFailureHandler');
})
.hello();
});
}
これはWebアプリケーション側よりGAS上の関数を実行する記載方法で以下のような構文になります。
google.script.run.withSuccessHandler(__コールバック関数__}).実行するGASの関数名();
実行するGASの関数名
となっている所にGoogle Apps Script側の任意の関数名を記載します。これだけでクライアント側とGoogle Apps Script側で連携する事が出来てしまいます。
上記、もし何かのお役に立てばお使い頂ければ幸いです。
宜しくお願い致します。