LoginSignup
0
0

【GAS】tsからjsファイルにバンドルしたコードをGASのエディタ上でデバッグできる状態に修正する

Last updated at Posted at 2024-05-02

「TypeScript+clasp+esbuild」でGASのローカル開発を便利にしたものの、そのままではデプロイした後にGASのエディタでデバッグすることができないため、
GASのエディタに反映されるタイミングで、デバッグできる状態にする方法を紹介します。

プロジェクト構成

.
├── dist/
│    ├── appsscript.json
│    └── main.js //バンドルされたファイル
├── src/
│    ├── main.ts
│    └── ... //他のtsファイル
├── .clasp.json
├── esbuild.js
├── package.json
├── tsconfig.json
└── updateFileContents.js //今回紹介するファイル

環境構築は以下の記事を参考にしています。
https://zenn.dev/funteractiveinc/articles/776b5812833475

問題点

バンドルされたmain.jsが以下の状態となっているため、そのままではGASのエディタでデバッグすることができません。

※バンドルとは、複数のファイルやモジュールを一つのファイルにまとめるプロセスのことを指します。

main.js
let global = this;

"use strict";
(() => {
 // ここにmain.tsの内容がバンドルされる
})();

(() => {})();が自動で付与されてしまう

解決策1(手動修正)

GASのエディタ上で、(() => {})();を削除する。

デプロイの度に手動で修正する必要があるため、めんどくさい😇

解決策2(自動修正)

バンドル後に自動で(() => {})();を削除し、その状態でデプロイする。

設定方法

以下のnodeファイルを作成する。(Copilotに生成してもらった)
※削除するだけだとインデントが気持ち悪いので修正してます。

updateFileContents.js
import { promises as fs } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const filePath = join(__dirname, './dist/main.js');

async function updateFileContents() {
  try {
    let data = await fs.readFile(filePath, 'utf8');
    let lines = data.split('\n');

    const useStrictIndex = lines.findIndex(line => line.includes('"use strict";'));
    if (useStrictIndex !== -1 && lines[useStrictIndex + 1].trim() === '(() => {') {
      lines.splice(useStrictIndex + 1, 1); // "use strict"; の1行下の `(() => {` を削除
    } else {
      throw new Error('Could not find "(() => {" after "use strict";');
    }

    if (lines[lines.length - 2].trim() === '})();') {
      lines.splice(lines.length - 2, 1); // 下から2行目の `})();` を削除
    } else {
      throw new Error('Could not find "})();"" before the last line');
    }

    // 各行のインデントを修正
    let modifiedData = lines.map(line => line.replace(/^ {2}/, '')).join('\n');

    await fs.writeFile(filePath, modifiedData, 'utf8');
    console.log('File has been modified successfully.');
  } catch (err) {
    console.error('Error modifying the file:', err);
  }
}

updateFileContents();

で、以下の順でコマンドを実行すればOK

node esbuild.js
node updateFileContents.js
npm run push

▼tips
以下のようにしておけば、npm run deployをコマンド実行するだけで上記の3つのコマンドが実行されます。

package.json
{
  "scripts": {
    "build": "node esbuild.js",
    "push": "clasp push",
    "fix": "node updateFileContents.js",
    "deploy": "npm run build && npm run fix && npm run push",
  }
}
0
0
0

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
0
0