clasp を使って Google Apps Script のスクリプトを作成する

Posts

clasp は Google ドライブにある Google Apps Script プロジェクトを操作できる CLI ツールです。

clasp で Google Apps Script(以降、GAS)を扱うメリットは次のとおり。

  • ローカルでファイルを作成するので、Git 管理できる。
  • TypeScript をサポートしており(v1.5.0 より対応)、ES2015 で書ける。

この記事では、clasp を利用して GAS のスクリプトファイルを TypeScript で作成しアップロードする手順を説明します。

動作を確認した環境

  • Node.js v8.15.1
  • clasp v2.1.0

clasp のインストールとログイン

  1. 次のコマンドを実行し、clasp をインストールします。
$ npm i @google/clasp -g
Installed @google/clasp@2.1.0
  1. Google アカウントにログインします。次のコマンドを実行すると、ブラウザが立ち上がります。Google アカウントへのログインを要求されるのでログインします。

    $ clasp login
    Logging in globally...
    🔑 Authorize clasp by visiting this url:
    https://accounts.google.com/xxx
    
    Authorization successful.
    
  2. Google Apps Script API を有効化します。

    1. Google Apps Script のユーザー設定を開きます。
    2. [Google Apps Script API]をクリックし、オンに設定します。

プロジェクトの作成

  1. clasp create コマンドでプロジェクトを作成する。 コマンド実行後、プロジェクトの種類を選択します。今回はスクリプトファイルのみのため、「standalone」を選択します。
mkdir sample
cd sample

$ clasp create sample
? Clone which script? (Use arrow keys)
 standalone
  docs
  sheets
  slides
  forms
  webapp
  api

Created new standalone script: https://script.google.com/d/xxxxx/edit
Cloned 1 file.
└─ appsscript.json

appsscript.json が作成されます。

  1. npm init で初期化します。 基本的に Enter キーでスキップしますが、entry pointのときだけ、「index.ts」と入力しておきます。 最後に Is this OK? (yes) と尋ねられるので、「yes」と入力します。

    $ npm init
    Press ^C at any time to quit.
    package name: (sample)
    version: (1.0.0)
    description:
    entry point: (index.js) index.ts
    test command:
    git repository:
    keywords:
    author:
    license: (ISC)
    About to write to /Users/chick-p/workspace/sample/package.json:
    
    {
      "name": "sample",
      "version": "1.0.0",
      "description": "",
      "main": "index.ts",
      "dependencies": {},
      "devDependencies": {},
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
    
    Is this OK? (yes) yes
    
  2. GAS の型定義ファイルをインストールします。

    npm i @types/google-apps-script --save-dev
    
  3. スクリプトファイルを作成します。

    vim index.ts
    
    // index.ts
    function main() {
      console.log('Hello World');
    }
    
  4. clasp pushコマンドで、クラウドの GAS プロジェクトへアップロードします。

    clasp push
    

動作確認

クラウドの GAS プロジェクトを確認すると、GAS フォーマットに変換されたファイル(index.gs)がアップロードされています。

// index.gs
// Compiled using ts2gas 1.6.2 (TypeScript 3.4.4)
var exports = exports || {};
var module = module || { exports: exports };
function main() {
  console.log('Hello World');
}

以上。