在 Cloud Functions 中使用 TypeScript
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
如果開發人員偏好以 TypeScript 編寫函式,Cloud Functions 提供兩種支援:
- 建立及設定 TypeScript 專案,以便在初始化時自動轉譯 (
firebase init functions
)。
- 透過部署前掛鉤,在部署時將現有的 TypeScript 來源轉譯為 JavaScript。
按照本指南的說明,您可以將現有的 JavaScript 專案遷移至 TypeScript,並繼續使用前置部署掛鉤轉譯原始碼,藉此部署函式。與純 JavaScript 相比,TypeScript 在編寫函式時有許多優勢:
- TypeScript 支援最新的 JavaScript 功能 (例如 async/await),可簡化 Promise 管理作業
- Cloud Functions 檢查工具會在您編寫程式碼時,醒目顯示常見問題
- 型別安全可協助您避免已部署函式發生執行階段錯誤
如果您是 TypeScript 新手,請參閱 5 分鐘學會 TypeScript。
使用 TypeScript 初始化新的 Cloud Functions 專案
在新目錄中執行 firebase init functions
。這項工具提供選項,讓您使用 JavaScript 或 TypeScript 建構專案。選擇「TypeScript」,輸出下列專案結構:
myproject
+- functions/ # Directory containing all your functions code
|
+- package.json # npm package file describing your Cloud Functions code
|
+- tsconfig.json
|
+- .eslintrc.js # Optional file if you enabled ESLint
+- tsconfig.dev.json # Optional file that references .eslintrc.js
|
+- src/ # Directory containing TypeScript source
| |
| +- index.ts # main source file for your Cloud Functions code
|
+- lib/
|
+- index.js # Built/transpiled JavaScript code
|
+- index.js.map # Source map for debugging
初始化完成後,請取消註解 index.ts 中的範例,然後執行 npm run serve
,查看「Hello World」函式運作情形。
使用現有的 TypeScript 專案
如果您有現有的 TypeScript 專案,可以新增前置部署掛鉤,確保每次將程式碼部署到 Cloud Functions for Firebase 時,專案都會轉譯。您需要格式正確的 tsconfig.json
檔案和 Firebase 專案,並對 Firebase 設定進行下列修改:
編輯 package.json
,加入用來建構 TypeScript 專案的 Bash 指令碼。例如:
{
"name": "functions",
"scripts": {
"build": "npm run lint && tsc"
}
...
編輯 firebase.json
,新增前置部署掛鉤來執行建構指令碼。例如:
{
"functions": {
"predeploy": "npm --prefix functions run build",
}
}
完成這項設定後,firebase deploy --only functions
指令就會建構 TypeScript 程式碼,並以函式形式部署。
將現有的 JavaScript 專案遷移至 TypeScript
如果您有以 JavaScript 初始化及開發的現有 Cloud Functions 專案,可以將其遷移至 TypeScript。強烈建議您先建立 Git 檢查點或其他備份,再開始操作。
如何遷移現有的 JavaScript Cloud Functions 專案:
- 建立 Git 檢查點,並儲存現有 JavaScript 來源檔案的副本。
- 在專案目錄中執行
firebase init functions
,並在系統提示您選擇函式撰寫語言時選取 TypeScript
。
- 系統提示是否要覆寫現有的
package.json
檔案時,請選取「否」,除非您確定不想保留現有檔案。
- 刪除目錄
functions/src
中的 index.ts
,並換成現有的原始碼。
- 在初始化時建立的
tsconfig.json
檔案中,將編譯器選項設為允許 JavaScript:"allowJs": true
。
- 將儲存的
package.json
檔案複製到 functions
目錄,並編輯該檔案,將 "main"
設為 "lib/index.js"
。
同樣在 package.json
中,為 TypeScript 新增建構指令碼,如下所示:
{
"name": "functions",
"scripts": {
"build": "npm run lint && tsc"
}
...
執行 npm install --save-dev typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser
,將 "typescript"
新增為開發依附元件。
如要取得所有依附元件,請執行 npm install --save @types/<dependency>
。
視需要將原始碼從 .js 重新編寫為 .ts。
模擬 TypeScript 函式
如要在本機測試 TypeScript 函式,可以使用「在本機執行函式」一文所述的模擬工具。使用這些工具前,請務必先編譯程式碼,因此請在函式目錄中執行 npm run build
,再執行 firebase emulators:start
或 firebase functions:shell
。或者,您也可以執行 npm run serve
或 npm run shell
做為捷徑;這兩個指令都會執行建構作業,並提供/啟動函式殼層。
TypeScript 專案的函式記錄
在 firebase deploy
期間,專案的 index.ts
會轉譯為 index.js
,這表示 Cloud Functions 記錄會輸出 index.js
檔案的行號,而不是您編寫的程式碼。為了方便您在 index.ts
中找出對應的路徑和行號,firebase deploy
會建立 functions/lib/index.js.map
。您可以在偏好的 IDE 中使用這個來源對應,也可以透過 Node.js 模組使用。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-17 (世界標準時間)。
[null,null,["上次更新時間:2025-08-17 (世界標準時間)。"],[],[],null,["\u003cbr /\u003e\n\nFor developers who prefer to write functions in TypeScript,\nCloud Functions provides two types of support:\n\n- Create and configure TypeScript projects for automatic transpilation at initialization (`firebase init functions`).\n- Transpile existing TypeScript source to JavaScript at deploy time via a [predeploy hook](/docs/cli#hooks).\n\nFollowing instructions in this guide, you can migrate an existing\nJavaScript project to TypeScript and continue deploying functions using a\npredeploy hook to transpile your source code.\nTypeScript offers many benefits over vanilla JavaScript\nwhen writing functions:\n\n- TypeScript supports latest JavaScript features like async/await, simplifying promise management\n- A Cloud Functions linter highlights common problems while you're coding\n- Type safety helps you avoid runtime errors in deployed functions\n\nIf you're new to TypeScript, see [TypeScript in 5 minutes](http://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html).\n\nInitializing a new Cloud Functions project with TypeScript\n\nRun `firebase init functions` in a new directory. The tool gives you options to build\nthe project with JavaScript or TypeScript. Choose **TypeScript** to output the\nfollowing project structure: \n\n myproject\n +- functions/ # Directory containing all your functions code\n |\n +- package.json # npm package file describing your Cloud Functions code\n |\n +- tsconfig.json\n |\n +- .eslintrc.js # Optional file if you enabled ESLint\n +- tsconfig.dev.json # Optional file that references .eslintrc.js\n |\n +- src/ # Directory containing TypeScript source\n | |\n | +- index.ts # main source file for your Cloud Functions code\n |\n +- lib/\n |\n +- index.js # Built/transpiled JavaScript code\n |\n +- index.js.map # Source map for debugging\n\nOnce initialization is complete, uncomment the sample in index.ts and run\n`npm run serve` to see a \"Hello World\" function in action.\n\nUsing an existing TypeScript project\n\nIf you have an existing TypeScript project, you can add a predeploy hook to\nmake sure your project is transpiled every time you deploy your code to\nCloud Functions for Firebase. You'll need a\nproperly formed `tsconfig.json` file and a Firebase project, and you'll need\nto make the following modifications to your Firebase configuration:\n\n1. Edit `package.json` to add a bash script to build your TypeScript project. For example:\n\n {\n \"name\": \"functions\",\n \"scripts\": {\n \"build\": \"npm run lint && tsc\"\n }\n ...\n\n2. Edit `firebase.json` to add a predeploy hook to run the build script. For example:\n\n {\n \"functions\": {\n \"predeploy\": \"npm --prefix functions run build\",\n }\n }\n\nWith this configuration, a `firebase deploy --only functions` command\nbuilds your TypeScript code and deploys it as functions.\n\nMigrating an existing JavaScript project to TypeScript\n\nIf you have an existing Cloud Functions project that you initialized\nand developed in JavaScript, you can migrate it to\nTypeScript. You're strongly encouraged to create a git checkpoint or other\nbackup before starting.\n\n**To migrate an existing JavaScript Cloud Functions project:**\n\n1. Create a git checkpoint and save copies of your existing JavaScript source files.\n2. In the project directory, run `firebase init functions` and select `TypeScript` when prompted for a language for writing functions.\n3. When prompted whether to overwrite the existing `package.json` file, select **No** unless you are sure you don't want to keep the existing file.\n4. Delete `index.ts` in the directory `functions/src`, replacing it with your existing source code.\n5. In the `tsconfig.json` file created at initialization, set the compiler options to allow JavaScript: `\"allowJs\": true`.\n6. Copy your saved `package.json` file into the `functions` directory, and edit it to set `\"main\"` to `\"lib/index.js\"`.\n7. Also in `package.json`, add a build script for TypeScript like the following:\n\n {\n \"name\": \"functions\",\n \"scripts\": {\n \"build\": \"npm run lint && tsc\"\n }\n ...\n\n8. Add `\"typescript\"` as a dev dependency by running `npm install --save-dev typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser`.\n\n9. For all dependencies, run `npm install --save @types/\u003cdependency\u003e`.\n\n10. Rewrite source code from .js to .ts as desired.\n\nEmulating TypeScript functions\n\nTo test TypeScript functions locally, you can use the emulation tools described\nin [Run functions locally](/docs/functions/local-emulator). It's important to\ncompile your code before using these tools, so make sure to run `npm run build`\ninside your functions directory before running `firebase emulators:start` or\n`firebase functions:shell`. Alternatively, run `npm run serve` or\n`npm run shell` as a shortcut; these commands both run the build and\nserve/start the functions shell.\n\nFunctions logs for TypeScript projects\n\nDuring `firebase deploy`, your project's `index.ts` is transpiled to `index.js`,\nmeaning that the Cloud Functions log will output line numbers from the\n`index.js` file and not the code you wrote. To make it easier for you to find the\ncorresponding paths and line numbers in `index.ts`,\n`firebase deploy` creates `functions/lib/index.js.map`. You can use this source\nmap in your preferred IDE or via a [node module](https://github.com/evanw/node-source-map-support)."]]