在 Cloud Functions 中使用 TypeScript
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
对于希望使用 TypeScript 编写函数的开发者,Cloud Functions 提供了两种支持方案:
- 创建并配置 TypeScript 项目,然后在初始化 (
firebase init functions
) 时自动进行转译。
- 利用部署前钩子在部署时将现有 TypeScript 源代码转译为 JavaScript。
按照本指南中的说明,您可以将现有 JavaScript 项目迁移至 TypeScript,并使用部署前钩子来转译源代码,以继续部署函数。
就编写函数而言,TypeScript 相比原版 JavaScript 有诸多优势:
- TypeScript 支持最新的 JavaScript 功能(例如 async/await),简化了 promise 管理
- 您编写代码时,Cloud Functions linter 会标出一些常见问题
- 类型安全性有助于避免所部署的函数中的运行时错误
如果您是 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 添加一个如下所示的 build 脚本:
{
"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 函数,您可以使用在本地运行函数中所述的模拟工具。在使用这些工具之前必须编译代码,因此您在运行 firebase emulators:start
或 firebase functions:shell
之前,请务必在函数目录内运行 npm run build
。或者,将 npm run serve
或 npm run shell
作为快捷方式运行;这些命令都运行 build 并提供/启动函数 shell。
TypeScript 项目的 Functions 日志
在 firebase deploy
期间,您的项目的 index.ts
将被转译为 index.js
,也就是说,Cloud Functions 日志将输出 index.js
文件中的行号,而非您编写的代码。为了让您更方便地找到 index.ts
中对应的路径和行号,firebase deploy
会创建 functions/lib/index.js.map
。您可以在您偏好的 IDE 中或通过节点模块使用此源代码映射文件。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-17。
[null,null,["最后更新时间 (UTC):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)."]]