对于喜欢在 TypeScript 中编写函数的开发人员,Cloud Functions 提供了两种类型的支持:
- 创建和配置 TypeScript 项目以在初始化时自动转换(firebase
firebase init functions
)。 - 在部署时通过预部署挂钩将现有 TypeScript 源代码转换为 JavaScript。
按照本指南中的说明,您可以将现有的 JavaScript 项目迁移到 TypeScript,并使用预部署挂钩继续部署函数以转译您的源代码。在编写函数时,TypeScript 比 vanilla 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
以添加 bash 脚本来构建您的 TypeScript 项目。例如:{ "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 函数,您可以使用在本地运行函数中描述的仿真工具。在使用这些工具之前编译您的代码很重要,因此请确保在运行firebase emulators:start
或firebase functions:shell
之前在您的函数目录中运行npm run build
。或者,运行npm run serve
或npm run shell
作为快捷方式;这些命令都运行构建和服务/启动函数 shell。
TypeScript 项目的函数日志
在 firebase firebase deploy
期间,您项目的index.ts
被转换为index.js
,这意味着 Cloud Functions 日志将从index.js
文件输出行号,而不是您编写的代码。为了方便您在 index.ts 中找到对应的路径和行号, index.ts
firebase deploy
创建了functions/lib/index.js.map
。您可以在首选 IDE 中或通过节点模块使用此源映射。