我最近部署了一个TypeScript项目来使用index.ts中的所有内容来构建firebase函数。一切正常,但是当我开始重构我的代码时,我很快意识到Firebase无法识别index.ts之外的文件(或将快速应用程序包装在functions.https.onRequest()
中的文件(中指定的路由。
我复制了以下问题:
//index.ts
import * as functions from 'firebase-functions';
import * as express from "express";
export const expressApp = express();
expressApp.get("/hi", (req, res)=> {
res.send("hi");
})
export const TestApp = functions.https.onRequest(expressApp);
添加"/hello"
路由的同一目录中的外部文件。
//external.ts
import { expressApp } from "./index";
expressApp.get("/hello", (req, res)=> {
res.send("hello")
})
我使用firebase-deploy
后,index.ts 中的"/hi"
路由有效,但 external.ts 中的"/hello"
路由不起作用(Cannot GET /hello
(。
我的猜测是,测试应用在被任何外部文件调用之前就被导出到 firebase-functions。
有没有办法在 TypeScript 项目中解决这个问题?
启动项目时,将执行index.ts
中的代码,但由于它根本不引用external.ts
,因此永远不会执行该代码。
相反,你可以做的是从index.ts
内部调用external.ts
,然后通过传入要修改express
应用来调用它。
//index.ts
import * as functions from 'firebase-functions';
import * as express from "express";
import {attachRoutes: attachExternalRoutes} from "./external";
export const expressApp = express();
expressApp.get("/hi", (req, res)=> {
res.send("hi");
})
attachExternalRoutes(expressApp); // attaches routes in external
export const TestApp = functions.https.onRequest(expressApp);
//external.ts
export function attachRoutes(expressApp) {
expressApp.get("/hello", (req, res)=> {
res.send("hello")
})
}