Firebase 函数无法编译 TypeScript 和 ES 模块

问题描述 投票:0回答:1

我最近使用默认设置将 Firebase Functions 添加到我的项目中(除了更改

"main": "src/index.ts",
中的值
package.json
,因为默认路径未指向正确的文件)。

这是我的工作代码:

// index.ts

const { initializeApp } = require('firebase-admin/app');
const { onValueCreated } = require('firebase-functions/v2/database');
const { logger } = require('firebase-functions');

initializeApp();

exports.testFn = onValueCreated(
  '/users/{uid}/company/accounts/{accId}',
  (event) => {
    logger.log(event);
  }
);

就像我说的,它有效 - 我在 Firebase 模拟器中获得了正确的日志信息。 但是,当我应用更改时:

// index.ts

// Switched imports from require to ESM
import { initializeApp } from 'firebase-admin/app';
import { onValueCreated } from 'firebase-functions/v2/database';
import { logger } from 'firebase-functions';

initializeApp();

exports.testFn = onValueCreated(
  '/users/{uid}/company/accounts/{accId}',
  (event: any) => { // <-- added ': any' type to event, so it does not show .ts error
    logger.log(event);
  }
);

我得到的只是

shutdown requested via /__/quitquitquit

!!  functions: Failed to load function definition from source: FirebaseError: Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

我检查过,这两个更改都会导致该错误:我无法导入 ES 模块或使用类型。 我检查了一下,我已经将

typescript
安装在
package.json
中。在 ESM 导入结束时写入扩展(如
.js
.ts
)也不起作用。

typescript firebase google-cloud-functions es6-modules
1个回答
0
投票

我找到了问题的答案。它并不完美,但它有效。

我使用了不正确的
firebase emulators:start
命令。

由 CLI Firebase Functions 项目生成,内部有自己的命令

package.json
:

    "build": "tsc",
    "build:watch": "tsc --watch",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"

我们应该使用

npm run serve
来代替。 同时将
"main": "lib/index.js"
保留在
package.json
中。现在这个解决方案会将 TypeScript 代码编译为 JavaScript 并将其放入
lib/index.js
中,我们的应用程序可以同时使用 ES 模块和 TypeScript。

重新编译问题

我不知道如何在保存时强制重新编译,即使在

 "compileOnSave": true
中设置了
tsconfig.json
。我的解决方法是打开第二个终端并在每次需要重新编译时使用
npm run build

如果有人(或我)能找到解决方案,我将编辑该帖子。

Firebase 模拟器中的更多服务

我还从

--only functions
中的
serve
命令中删除了
package.json
,因此我所需的所有 Firebase 服务都在本地模拟。

© www.soinside.com 2019 - 2024. All rights reserved.