当我尝试 运行 在本地运行时 firebase 显示错误

firebase show error when i try to run functions locally

每当我在 CLI 中使用本地模拟器 运行 函数时显示 Firebase 错误

$ firebase emulators:start --only functions

Starting emulators: ["functions"]

functions: Using node@8 from host.

functions: Emulator started at http://localhost:5001

functions: Watching "E:\dir\functions" for Cloud Functions...

Error: Cannot find module 'E:\dir\functions'

at Function.Module._resolveFilename (module.js:548:15)

at Function.Module._load (module.js:475:25)

at Module.require (module.js:597:17)

at require (internal/module.js:11:18)

at C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:459:29

at Generator.next ()

at C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:7:71

at new Promise ()

at __awaiter (C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:3:12)

at main (C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:421:12)

Your function was killed because it raised an unhandled error.

我用typescript写云函数

这是我的index.ts

import * as functions from 'firebase-functions';
import * as admin from "firebase-admin";

var cert = require("./skey.json");

admin.initializeApp({
    credential: admin.credential.cert(cert),
    databaseURL: "https://bhau-tk.firebaseio.com"
});

exports.basicHTTP = functions.https.onRequest((req, res) => {
    res.send("Hello world!!");
})

package.json包含

{
  "name": "functions",
  "scripts": {
    "lint": "tslint --project tsconfig.json",
    "build": "tsc",
    "serve": "npm run build && firebase serve --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "main": "lib/index.js",
  "dependencies": {
    "firebase-admin": "~7.0.0",
    "firebase-functions": "^2.3.0",
    "firebase-functions-test": "^0.1.6"
  },
  "devDependencies": {
    "tslint": "^5.12.0",
    "typescript": "^3.2.2"
  },
  "private": true
}

项目结构

您应该记住,您的项目配置是在 src 下编译 TS 源文件并将生成的 JavaScript 文件放在 lib 中。因此,您应该参考与该位置相关的函数文件夹中的内容。

由于你编译的 index.js 在 lib 中,而你的 skey.json 文件在 src 下,你必须这样引用它:

var cert = require("../src/skey.json");

但是,我不会那样做。我将 skey.json 放在函数文件夹中(因为它不是源代码),并像这样引用它:

var cert = require("../skey.json");