1分でできるFirebase Hostingに静的サイトをデプロイする方法

Firebase Hostingとは

Firebase HostingとはHTMLファイルなどでできたコンテンツをアップロードできる高速で安全性の高いホスティングのGoogleのサービス。

Googleアカウントを持っていれば基本無料で使用できる。

Firebase Hostingを使用すれば以下のようなページを簡単にWeb上にアップロードできる。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hosting test</title>
</head>
<body>
<h1>Hosting test</h1>
</body>
</html>

https://hosting-test-c7361.web.app

Firebase Hosting プロジェクト作成手順

Firebase HostingでデプロイするにはまずFirebaseコンソールでプロジェクトを追加する。プロジェクト名は仮でhosting-testにした。
1分でできるFirebase Hostingに静的サイトをデプロイする方法

ちなみに手順2でGoogleアナリティクスを有効にするかの選択肢があり、推奨と書かれているので有効にしたほうが良いように見えるが、使用しないのであればオフにして問題ない。

https://console.firebase.google.com/u/0/

「プロジェクトを作成」を押すと処理が実行される。(数十秒かかる)

プロジェクトの作成が完了するとFirebaseコンソールに表示される。

Firebase Hosting デプロイ手順

1. npm から Firebase CLI をインストールする。

Firebase CLIがインストールされているかはfirebase -Vでわかる。

すでにインストールされていてもバージョンが古くなっていたら以下のコマンドで最新をインストールしよう。(失敗する場合はsudoを付ける)

npm install -g firebase-tools

次にfirebase loginでログインする。

もしログイン中の状態になっていても、以前にログインしたのがかなり前だとデプロイ時にエラーになることがあるので、一度ログアウトしてから再度ログインしたほうが良い。

firebase logout && firebase login

ログインが完了したらディレクトリを作成して、その中に移動してfirebase initを実行する。

mkdir hosting-test; cd hosting-test; firebase init

firebase initを実行すると選択肢が出るので下キーを3回押したあとスペースキーを押してHostingを選択してEnterキーを押す。

スペースキーを押しても選択できない場合は、shiftキーを押しながらスペースキーを押す。

そのあとの選択肢は以下を選択する。
(これら以外は全部Enterを押して設定)

? Please select an option: Use an existing project
? Select a default Firebase project for this directory: (Use arrow keys)
❯ hosting-test-c7361 (hosting-test) 

以上の手順が完了すればfirebase deployを実行するだけでpublicフォルダのindex.htmlなどのファイルがデプロイされて、以下のようなURLで見られるようになる。

$ firebase deploy

=== Deploying to 'hosting-test-c7361'...

i  deploying hosting
i  hosting[hosting-test-c7361]: beginning deploy...
i  hosting[hosting-test-c7361]: found 2 files in public
✔  hosting[hosting-test-c7361]: file upload complete
i  hosting[hosting-test-c7361]: finalizing version...
✔  hosting[hosting-test-c7361]: version finalized
i  hosting[hosting-test-c7361]: releasing new version...
✔  hosting[hosting-test-c7361]: release complete

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/hosting-test-c7361/overview
Hosting URL: https://hosting-test-c7361.web.app

https://hosting-test-c7361.web.app