LoginSignup
5

More than 5 years have passed since last update.

Firebase CLIで作成したTypeScriptのFirebase Cloud Functionsのプロジェクトをファイル分割

Posted at

index.tsに記述した複数のFunctionを別ファイルに分割する方法です。
特別なことはしていませんが、メモとして残しておきます。

前提

$ firebase -V
3.16.0

前提として、Firebase CLI(firebase-tools)にて次のように初期化したプロジェクトを前提に進めます。

$ mkdir firebase-functions && cd firebase-functions
$ firebase init functions
-- 略
? Select a default Firebase project for this directory: [create a new project]
-- 略
? What language would you like to use to write Cloud Functions? TypeScript
? Do you want to use TSLint to catch probable bugs and enforce style? Yes
-- 略
? Do you want to install dependencies with npm now? Yes

ファイル分割しないパターン

Firebase CLIを使ってCloud Functionsを使用するプロジェクトを初期化すると、functions/src以下に、index.tsが作成されます。
同一のプロジェクトFunctionを追加する場合、次のようにこのファイルに追記していけば、firebase deploy --only functions実行時に複数Functionが同時にデプロイされます。

index.ts
import * as functions from 'firebase-functions';

export const helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello World!");
});

export const helloFirebase = functions.https.onRequest((request, response) => {
 response.send("Hello Firebase!");
});

export const helloTypeScript = functions.https.onRequest((request, response) => {
 response.send("Hello TypeScript!");
});

ファイル分割する

Functionが増えてきたときに辛いので、ファイル分割してみましょう。
TypeScriptのビルド設定が記述されているtsconfig.jsonを見てみると、次のようにfunctions/src以下が対象として指定されているので、何も考えずTypeScriptのモジュールシステムに従ってファイルをFunctionごとに分割していけばよさそうです。

tsconfig.json
{
  "compilerOptions": {
    "lib": ["es6"],
    "module": "commonjs",
    "noImplicitReturns": true,
    "outDir": "lib",
    "sourceMap": true,
    "target": "es6"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

まずは、functions/src以下にFunctionごとのファイルhelloWorld.tshelloFirebase.tshelloTypeScript.tsを作成します。

helloWorld.ts(例)
import * as functions from 'firebase-functions';

export const helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello World!");
});

index.ts側では次のようにimport/exportするだけです。

index.ts
import { helloWorld } from './helloWorld';
import { helloFirebase } from "./helloFirebase";
import { helloTypeScript } from './helloTypeScript';

export {
  helloWorld,
  helloFirebase,
  helloTypeScript
}

デプロイについて

プロジェクト内の全てのFunctionをデプロイする場合

$ firebase deploy --only functions

指定したFunctionのみをデプロイする場合(次の例ではhelloWorldのみをデプロイするように指定)

$ firebase deploy --only functions:helloWorld

参考

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
What you can do with signing up
5