LoginSignup
5
7

More than 3 years have passed since last update.

TypeScript + webpack + npm + claspでGAS開発

Last updated at Posted at 2020-08-23

完成形

├ dist/
   └ main.js (コンパイルされたjsファイル)
│  └ appsscript.json
├ src/ (開発を行うディレクトリ)
├ .clasp.json
├ package.json
├ tsconfig.json
├ webpack.config.js
├ yarn.lock

1. パッケージのインストール

package.jsonを作成

yarn init -y

必要なパッケージをインストール

yarn add -D @google/clasp typescript ts-loader webpack webpack-cli gas-webpack-plugin cpx @types/google-apps-script @types/node

2. TypeScript の設定

tsconfig.jsonを作成する

yarn tsc --init

お好みで設定してください。

tsconfig.json
{
  "compilerOptions": {
    "sourceMap": true,
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node"
  }
}

3. webpack.config.js を作成

webpack.config.js ファイルを作成して以下のコードをコピペ

webpack.config.js
const path = require('path');
const GasPlugin = require('gas-webpack-plugin');

module.exports = {
    entry: {
        main: path.join(__dirname, 'src', 'main.ts')
    },
    output: {
        filename: '[name].js',
        path: path.join(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: 'ts-loader'
            }
        ]
    },
    resolve: {
        extensions: [
            '.ts',
            '.js'
        ]
    },
    plugins: [
        new GasPlugin(),
    ]
};

4. claspでGASプロジェクトを作成

googleにログイン
ブラウザが開かれるのでアカウントを選択してログインする

yarn clasp login

プロジェクトを作成する
今回はstandaloneを選択

yarn clasp create [プロジェクト名]

? Create which script? (Use arrow keys)
❯ standalone
  docs
  sheets
  slides
  forms
  webapp
  api

.clasp.json ファイルが作成されるのでそれを編集する
rootDirにルートディレクトリdistを設定

.clasp.json
{
  "scriptId":"[スクリプトID]",
  "rootDir": "dist"
}

5. 開発

srcディレクトリで開発を行うためsrcディレクトリを作成する
main.tsファイルを作成し、サンプルコードを書いていく

main.ts
declare var global: any;

global.doGet = () => {
    return ContentService.createTextOutput('Hello World');
}

yarnのbuildコマンドとdeployコマンドを作成

package.json
{
  "scripts": {
    "build": "rimraf dist && webpack && cpx appsscript.json dist",
    "deploy": "yarn build && clasp push"
  }
}

gasにdeployする

yarn deploy

6. 公開する

上記のコードをWebアプリケーションとして公開するとこのような感じになります。
スクリーンショット 2020-08-23 11.28.09.png

以上です。

5
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7