TypeScript 是 JavaScript 類型化超集合,可編譯為純 Apps Script。在開發 Apps Script 專案時使用 TypeScript 的好處如下:
本指南說明使用 TypeScript 開發 Apps Script 專案的部分常見工作。
需求條件
如果您還不熟悉 TypeScript,請先參閱 TypeScript 說明文件和 TypeScript 快速入門導覽課程,熟悉基本概念,再嘗試本指南所述的任何程序。
您必須具備下列工具,才能搭配 clasp
在 Apps Script 專案中使用 TypeScript。雖然在 Apps Script 中啟用 TypeScript 並非絕對需要使用 clasp
,但還是強烈建議您使用,因為這樣可大幅簡化相關程序。
在嘗試下述任何程序之前,請確認您已安裝下列以啟用本機開發環境:
- 節點和 npm
clasp
:npm install -g @google/clasp
- Apps Script 的類型定義:
npm i -S @types/google-apps-script
- Visual Studio Code (適用於 TypeScript IDE 自動完成功能)
如果您之前從未使用過 clasp
,請務必熟悉 clasp
說明文件
。
在 Clasp 專案中使用 TypeScript
您可以使用 clasp
快速建立新的本機 Apps Script 專案。這個指令會建立 Apps Script 專案的基礎 appsscript.json
和 Code.gs
。
如要在 App Script 檔案中使用 TypeScript,只要將副檔名從 gs
重新命名為 ts
即可。
編輯本機 TypeScript 檔案
您可以使用慣用的編輯器,在專案資料夾中將本機 TypeScript 檔案寫入為 .ts
檔案。
舉例來說,名為 index.ts
的檔案可能包含以下 TypeScript 程式碼:
const greeter = (person: string) => {
return `Hello, ${person}!`;
}
let user = 'Grant';
Logger.log(greeter(user));
您可以使用箭頭函式和字串內插 (${var}
) 等 ES6+ 功能編寫 TypeScript。當您將專案推送至 Apps Script 伺服器時,這些檔案就會轉譯為 Apps Script 結構。
上傳使用 TypeScript 的本機 Apps Script 專案
本機 TypeScript 和 Apps Script 檔案編輯完成後,您可以使用以下 clasp
指令將本機檔案上傳到 Google 雲端硬碟:
clasp push --watch
這個指令會監控 TypeScript 檔案變更,並使用 typescript
編譯程式碼,並使用 clasp
將專案上傳至 Google 雲端硬碟。
回報問題或提出功能要求
如果您在使用 clasp
工具時遇到問題,可以前往 GitHub 回報問題。
如果您遇到 TypeScript 本身的問題或錯誤,可以前往 TypeScript 的 GitHub 存放區回報問題。