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

hc8w905p  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(119)

我最近添加了Firebase函数到我的项目与默认设置(除了改变值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模块或使用类型。我检查了,我有package.json安装在typescript。在ESM导入结束时写入扩展名(如.js.ts)也不起作用。

uurv41yg

uurv41yg1#

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

我使用的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。同时保持package.json中的"main": "lib/index.js"不变。现在,这个解决方案将把TypeScript代码编译成JavaScript并将其放入lib/index.js中,我们的应用程序可以同时使用ES模块和TypeScript。

编译问题

我不知道如何在保存时强制重新编译,即使在tsconfig.json中设置了"compileOnSave": true。我的解决方法是打开第二个终端,每次需要重新编译时使用npm run build
如果有人(或我)会找到解决方案,我会编辑这篇文章。

Firebase Emulator中的更多服务

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

相关问题