firebaseのhostingで簡単に静的サイトをデプロイする方法

  • 2019年5月7日
  • 2019年5月7日
  • firebase

今回、firebaseのhostingを利用してHTML,CSSで制作したサイトをデプロイする手順についてご紹介します。

Firebaseとは?

Firebaseはgoogle社が提供するサービスです。firebaseのhostingを利用すると静的サイト、動的サイト(HTML、CSS、JavaScript など)を簡単に本番環境にデプロイ出来ます。また、サイトを修正する場合もワンクリックでロールバック(間違えをする前の状態)に戻せます。そのため、ポートフォリオ用のサイトを簡単にデプロイでき、エンジニア就職・転職する際のアピール材料にもなります。

Firebase Hosting | Firebase

Firebase Hosting provides fast and secure hosting for your web app, static and dynamic content, and microservices.

Firebaseの特徴

  • 簡単で素早くデプロイ
  • ワンクリックのロールバック

firebaseでデプロイするまでの手順

アカウント登録とプロジェクトの作成

firebaseを利用するにあたりgoogleアカウントを持っていない方はまずはアカウント登録をしてください。既にgoogleアカウントをお持ちの方はログインをしてfirebaseのコンソール画面へアクセスします。

コンソールへ移動したら「プロジェクトを追加」を選択。

今回、プロジェクト名「My First Project」とし、アナリティクスの地域を日本にします。それぞれの規約にチェックを入れ同意をしたらFirebase追加を押下します。

ディレクトリ構成の確認

プロジェクトを作成したら続いてディレクトリ構成の確認を行います。firebaseにデプロイする際はデプロイしたいファイル(index.htmlやcssファイル)をpublic配下に用意します。 今回、myprojectportfolio/public/index.htmlというディレクトリ構成になっています。

Node.jsのインストール

firebaseでデプロイする際にNode.jsが必要になるのでまだの方は以下のサイトからインストールします。今回は推奨版をインストールしました。

Node.js

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.

node.jsのインストールが完了したらnode.jsとNode Package Manager(npm)がインストールされているかコマンドでバージョンを確認します。以下のようにバージョンを確認出来たらインストールが正しくされています。

MacBook-puro$ node -v
v10.15.3
MacBook-puro$ npm -v
6.4.1

firebase-toolsのインストールとログイン

続いてコマンドでfirebase-toolsをインストールしていきます。sudo npm install -g firebase-toolsを実行しPCのパスワードを入力します。

MacBook-puro$ sudo npm install -g firebase-tools
Password:

コマンド上で以下のようなメッセージが表示されたらインストール完了です。


/usr/local/bin/firebase -> /usr/local/lib/node_modules/firebase-tools/lib/bin/firebase.js

> @google-cloud/functions-emulator@1.0.0-beta.6 postinstall /usr/local/lib/node_modules/firebase-tools/node_modules/@google-cloud/functions-emulator
> node scripts/upgrade-warning


If you're using the Emulator via the Firebase CLI, you can
disregard this message.

If you're upgrading @google-cloud/functions-emulator, these
are the recommended upgrade steps:

1.  Stop the currently running emulator, if any:

        functions stop

2.  Uninstall the current emulator, if any:

        npm uninstall -g @google-cloud/functions-emulator

3.  Install the new version of the emulator:

        npm install -g @google-cloud/functions-emulator

If you have trouble after upgrading, try deleting the config
directory found in:

    ~/.config/configstore/@google-cloud/functions-emulator

Then restart the emulator. You can also check for any renegade
Node.js emulator processes that may need to be killed:

    ps aux | grep node

+ firebase-tools@6.8.0
added 567 packages from 275 contributors in 32.388s

firebaseバージョン確認の際に表示されるエラーの対処の仕方

firebaseが正しくインストール出来ているかfirebase -Vで確認します。その際にアクセス権限の問題で以下のようなエラーが表示される場合があります。

MacBook-puro$ firebase -V

┌──────────────────────────────────────────────────────────────┐
│              firebase-tools update check failed              │
│             Try running with sudo or get access              │
│             to the local update config store via             │
│ sudo chown -R $USER:$(id -gn $USER) /Users/username/.config │
└──────────────────────────────────────────────────────────────┘
/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:53
				throw err;
				^

Error: EACCES: permission denied, open '/Users/username/.config/configstore/firebase-tools.json'
You don't have access to this file.

    at Object.openSync (fs.js:438:3)
    at Object.readFileSync (fs.js:343:35)
    at Configstore.get (/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:34:26)
    at new Configstore (/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:27:45)
    at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/configstore.js:4:18)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)

エラーの対処法として sudo chown -R ${USER} ~/.configを実行してください。

MacBook-puro:$ sudo chown -R ${USER} ~/.config

再度、firebaseのバージョンを確認してみます。

MacBook-puro:~ yanodaiki$ firebase -V
6.8.0

firebaseへログインする

コマンド上からfirebaseにログインします。firebase loginを実行するとgoogleアカウントのログイン画面に遷移するので、hostingのプロジェクトを作成したカウントでログインをし、Firebase CLIに対してのアクセスを許可してください。

oMacBook-puro$ firebase login
? Allow Firebase to collect anonymous CLI usage and error reporting information? Yes

Visit this URL on any device to log in:
https://accounts.google.com/o/oauth2/auth?client_id=5669-fgrhgmd47bqne6.apps.googleusercontent.com&scope=email%20https%3A%2F%2Fwww.googlea%2Fcloudplatformprojects.readonly%20htF%2Fwww.googleapis.com%2Fauth%2Ffirebase%20Fwww.googleapis.com%2Fauth%2Fcloud-platform&response_type=code&state=493&redirect_uri=http%3A%2F%2Flocalh005

Success!が表示されたらログイン完了です。

Waiting for authentication...

✔  Success! Logged in as ********@gmail.com

firebase listとfirebase initの実行

ログインが完了したらデプロイしたいフォルダのディレクトリへ移動します。今回の対象フォルダはmyprojectportfoloなので、移動出来たらfirebase listを実行します。するとnameとMy First Projectのリストが表示されます。

MacBook-puro:myprojectportfolo$ firebase list
┌──────────────────┬───────────────────────┬─────────────┐
│ Name             │ Project ID / Instance │ Permissions │
├──────────────────┼───────────────────────┼─────────────┤
│ My First Project │ positive-epax-000000  │ Owner       │
└──────────────────┴───────────────────────┴─────────────┘

リストに表示されたProject IDをコピーしたら続いてfirebase init –project=positive-epax-000000を実行します。–project=の後ろにProject IDを貼り付けてください。そうすると以下のようにコマンド上にFIREBASEが表示されます。

MacBook-puro:myprojectportfolo $ firebase init --project=positive-apex-*******

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /Users/username/myprojectportfolo

今回、hostingを使うのでHostingに移動してスペースキーを押下してください。

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

i  Using project positive-epax-****** (My First Project)

=== Hosting Setup

What do you want to use as your public directory?に対してはpublicを選択します。Configure as a single-page app (rewrite all urls to /index.html)にはNoと回答します。最後にFirebase initialization complete!が表示されたら設定完了です。

? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? No
✔  Wrote public/404.html
✔  Wrote public/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...
i  Writing gitignore file to .gitignore...

✔  Firebase initialization complete!

firebase deployを実行

firebaseにデプロイするためにfirebase deployを実行してください。Deploy complete!と表示されたらデプロイ完了です。コマンド上に表示されたHosting URLにアクセスします。

MacBook-puro:myprojectportfolo$ firebase deploy

=== Deploying to 'positive-apex-******'...

i  deploying hosting
i  hosting[positive-apex-******]: beginning deploy...
i  hosting[positive-apex-******]: found 102 files in public
✔  hosting[positive-apex-******]: file upload complete
i  hosting[positive-apex-******]: finalizing version...
✔  hosting[positive-apex-******]: version finalized
i  hosting[positive-apex-******]: releasing new version...
✔  hosting[positive-apex-******]: release complete

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/positive-epax-******/overview
Hosting URL: https://positive-epax-*******.firebaseapp.com

URLにアクセス後、以下のようなサイトが表示されたら無事にデプロイできてます。

自身で制作したサイトやアプリはfirebaseやherokuなどで簡単にデプロイでき、世の中に公開することができます。皆さんもポートフォリオをアピール材料にするために積極的に利用していきましょう!

firebaseの最新記事8件

>文系エンジニア大学生の技術ブログ

文系エンジニア大学生の技術ブログ

社会が多様化していく中、大学生の学生生活も多様であるべきと考えています。主にエンジニア向けにITやプログラミングなどの技術系と大学生向けに休学、留学、海外生活、トビタテ留学、長期インターンに関する記事を書いています。