我最近添加了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
)也不起作用。
1条答案
按热度按时间uurv41yg1#
我找到了问题的答案。它并不完美,但它工作。
我使用的
firebase emulators:start
命令不正确。由CLI生成Firebase Functions项目在
package.json
中有自己的命令:我们应该使用
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服务都在本地仿真。