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が同時にデプロイされます。
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ごとに分割していけばよさそうです。
{
"compilerOptions": {
"lib": ["es6"],
"module": "commonjs",
"noImplicitReturns": true,
"outDir": "lib",
"sourceMap": true,
"target": "es6"
},
"compileOnSave": true,
"include": [
"src"
]
}
まずは、functions/src
以下にFunctionごとのファイルhelloWorld.ts
、helloFirebase.ts
、helloTypeScript.ts
を作成します。
import * as functions from 'firebase-functions';
export const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello World!");
});
index.ts側では次のようにimport/exportするだけです。
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
参考