Firebase Functions ローカルで関数を実行する時に失敗する件について

Firebase Functionsは firebase-tools を使って、ローカルで関数を実行してテストできる。

結論

firebase functions:shell を使おう!

使い方はこちら

firebase.google.com

例えば、 myFunc という関数を定義したら、

firebase > myFunc.get()

とかで呼べるし、express で myFunc配下に関数 ( /greet ) がある場合には、

firebase > myFunc.get('/greet')

で呼べる。

インストール

少し手間取ります

npm もしくは yarn を使ってインストールする。

公式ガイドより

$ npm install --save firebase-functions@latest
$ npm install -g firebase-tools

※ firebase-functionsは@latestじゃなくても特に問題なさそう

いざ実行してみると、firebase-functions-testが必要と言われる。

⚠ The Cloud Functions emulator requires the module "firebase-functions-test" to be installed as a development dependency. To fix this, run "npm install --save-dev firebase-functions-test" in your functions directory.

言われる通りに dev-dependencies に追加

$ yarn add -D firebase-functions-test

とすると今度は、 node は version 8 じゃないとダメ!と言われてしまう。

The engine "node" is incompatible with this module. Expected version "8". Got "11.13.0"

しょうがないので、node を version 8 に。(nodebrewを入れておいてよかった)
手元にあったのが v8.15.1 だったのでそれにした。

$ nodebrew list
v6.17.1
v8.15.1
v10.15.3
v11.13.0

$ nodebrew use v8.15.1

再度 Try で インストール成功

$ yarn add -D firebase-functions-test

firebase functions:shellを実行してみると、エラー。

Error: Failed to load gRPC binary module because it was not installed for the current system
   ~~~
This problem can often be fixed by running "npm rebuild" on the current system

なんか rebuild しなさいとのこと。

$ npm rebuild

思っていたより早く終わって、もう一度 firebase functions:shell を実行するとうまく行った。

経緯

Google で 「firebase functions ローカル実行」とかで検索すると以下のページがヒットする。
firebase.google.com

ただし、firebase emulators:start は失敗する。

どうもこのローカルエミュレートの googlearchive/cloud-functions-emulator がメンテされなくなったみたいで「firebase-tools を使ってくれ」と書かれている。
Cloud Functions ローカル エミュレータ  |  Cloud Functions のドキュメント  |  Google Cloud

f:id:clash_m45:20190818232919p:plain
emu

検索するとこの cloud-functions-emulator を別途インストールしたらOKみたいな記事ばっかりだったので、
firebase functions:shellに置き換わってるみたいよ!というのが言いたかった。

環境情報

❯ firebase --version 6.12.0

追記

ちなみに cannot find module とか言ってエラーになるときは、モジュールがビルド出来ているか確認してください!

TypeScriptで書いてて、JavaScriptがビルドされてない状態で firebase functions:shell 打ってるとエラーになって「あれー?」となる。