11
5

More than 3 years have passed since last update.

Firebase Cloud Functionsの実行ファイルが見つからないときにやったこと

Posted at

概要

TypeScriptでFirebase Cloud Functionsを使っていたときの構成として実装をsrcで書いているが、
ユニットテストがTypeScriptで書きたくなったときに __tests__ などのディレクトリをrootに作成した場合、
デフォルトではコンパイル時libディレクトリに srcと __tests__ のディレクトリが作成される。
このときpackage.jsonのmainが "main": "lib/index.js" となっているのでFirebase Functionsの起動時にファイルが見つからないというエラーになる。

環境

ライブラリ バージョン 補足
typescript 3.7.2 コンパイルに必要
ttypescript 1.5.8 パスの変更などのpluginを利用する際に必要

解消方法

  1. mainで参照する起動ファイルをlib/src/index.jsにする
  2. そもそもlibディレクトリにsrcなどのディレクトリができないようにする

1. mainで参照する起動ファイルをlib/src/index.jsにする

実装としては、とりあえず以下のようにするだけ

package.json
{
  "main": "lib/src/index.js"
}

2. そもそもlibディレクトリにsrcなどのディレクトリができないようにする

TypeScriptのtsconfigでexcludeする

tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": false,
    "strict": true,
    "target": "es2017",
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    },
    "plugins": [{ "transform": "@zerollup/ts-transform-paths" }]
  },
  "compileOnSave": true,
  "exclude": ["node_modules", "__tests__"]
}

これで一旦buildと実行はうまくいくが、次にVSCodeのほうが__tests__のファイルにてpath解決ができなくなる。
そのため、上記ファイルからexcludeを削除して、以下のようなファイルを作成する

tsconfig.function.json
{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "__tests__"]
}

そして、build時の参照先のjsonを新たに作成したjsonに変更する

package.json
{
  "name": "functions",
  "scripts": {
    "lint": "tslint --project tsconfin.function.json",
    "build": "ttsc --project tsconfig.function.json",
    "dev": "firebase emulators:start --only functions",
    "serve": "npm run build && firebase serve --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "npm run build && firebase deploy --only functions",
    "logs": "firebase functions:log",
    "test": "jest"
  },
  "main": "lib/index.js"
}

こうするとVSCodeの参照はtsconfig.jsonのままなので、path参照はうまくいくようになる。

まとめ

まだそこまでTypeScriptとFirebase Cloud Functionを半年ぐらいだけど設定が色々あって覚えきれていない。
正直今回は1でいいとは思うが、もし何かで困ったときにこのあたりの設定を見つめ直すというのもありかもしれない

Firebase Functionsでdeployされるファイルはfirebase.jsonのsourceに書いてあるディレクトリとファイル全てになるため、
deploy時間を早くしたいとかの場合は、このあたりの設定も見直したほうが良さそう
ただ、そもそもFunctionsでそんなに大きなプロジェクトを作るほうが間違いな気もする。GAEとかでもいいのではないか?

11
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5