[Google Apps Script] TypeScript環境構築からgit clone まで

[概要]

・TypeScriptの環境を構築してGitにあげておきます。

・開発するときはgit cloneします。

・新しいリポジトリにpushします。

[目的]

Google Apps ScriptのTypeScript環境の準備。基本的には下記リンクを参考にしました。


[なぜTypeScript?]

型を定義できるのが良いです。あとvscodeで補完もききます。

Google Apps Scriptを使っているとReturnがスプレッドシートのオブジェクトかどうかで配列にいれられなかったりするので、少し複雑なアプリを作るときはあると便利です。

[構築方法]

まずnpmをインストールします。

$ npm init -y
$ npm install @google/clasp tslint -D 
$ npm install @types/google-apps-script -S

このテンプレートは今後も使うのでgitにあげておきます。gitでリポジトリをつくってから下のコマンドをうちます。

echo "# googleAppscriptsParts" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin git@github/gs.git
git push -u origin master

もし、

git push -u origin master

fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

というエラーがでてしまったら、SSHキーの再登録が必要です。以下のURLを参考に再登録をします。

そして、確認のために

ssh -T git@github.com

ユーザー名ががでてきたら登録問題なしです。

ちなみに、もし、間違えてnode_moduleを登録してしまったら、.gitignoreにnode_moduleを入れてから、以下の作業で削除します。

$ git rm -r --cached node_modules  
$ git status
$ git add .
$ git push -u origin master

作業するときはここからgit cloneします。

ちなみに、gitにはpullとcloneがあります。

どちらが良いのか調べると、

[質問]gitでのシステム開発を始める時、
・git clone
・git init + git pull
の2パターンで開発を始めています。
git cloneを使った方が良い気がしていますが、
上記2パターンの違いがわかっていないため、なぜcloneを使った方が良いのかが明確に把握できていません。ご存知の方がいらっしゃいましたら、ご教授下さい。

[回答] git clone は 
git init
リモートリポジトリの各種設定(※)
git pull
を一度にやってくれる便利コマンドのようなものです。楽でミスもないので、特に理由がなければ git clone を使うのがよいと思います。
※参考:initしてremote addするのとcloneするのの違い - hokaccha hamalog v3
また余談ですが git pull も、実際には git fetch + git merge を一度にやってくれる複合コマンドだったりします。
ということなので、cloneを使います。


ということで、git cloneをつかいます。

git clone <さっきのURL>

でクローンできます。

[新しいリポジトリに登録]

githubでリポジトリをつくってから、下記のコマンドでリモートリポジトリのURLを変更できます。

$ git remote set-url origin <new-url>
$ git add -A
$ git commit -m "All"
$ git push

ここでgitも下準備ができたので、さらにclaspの準備を始めます。

$ clasp create <好きな名前>  
$ clasp pull 

これでgoogleDriveにファイルができていると思います。あとは設定ファイルを書き換えます。

//.clasp.json を書き換えます。
{
"scriptId":"******-***************************************************",
"rootDir": "src"
}

src ディレクトリを作って、clasp pushの対象となるファイルを移動する。

$ mkdir src
$ mv appsscript.json src/
$ mv Code.js src/Code.ts


ここで、下のエラーがでます。

mv: rename Code.js to src/Code.ts: No such file or directory

なので直接つくります。

$ cd  src
$ touch Code.ts


appsscript.jsonのtimeZoneをかえます。カレンダーなどで、時間を使うときに泣きます。

//失敗例
{
"timeZone": "Japan/Tokyo",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER"
}


とかくとエラーがでました。正しくはJapan/Tokyoでなく、Asia/Tokyoです。

//JapanではなくAsia
{
"timeZone": "Asia/Tokyo",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER"
}

これで準備ができました。あとは開発をしていきます。


この記事が気に入ったらサポートをしてみませんか?