🐥

Vue3とFirebaseの連携

2023/06/09に公開

この記事の目標

  • Firebaseの設定
  • Vue3のプロジェクトにFirebaseの処理を追加
  • Vue3のプロジェクトにFirebaseエミュレータの導入

Firebaseの登場によりアウトプットの敷居が下がったと感じており、学生やITに興味ある人の手助けができればと考えております

環境構築に必要な事前準備の確認

事前準備で扱う物の説明や導入に関してはここでは省きます。
Vue3のプロジェクトは下記プロジェクトを使う
https://github.com/viviomega/vue-viviomega

導入記事は下記になります
https://zenn.dev/viviomega/articles/03fa1854a06205

JDKの導入

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

firebaseでプロジェクトを作成


上記画像の使ってみるのボタンを押下します

上記画像のプロジェクトを作成を押下します
後は画面の指示に従ってプロジェクトを作成します

webアプリケーションの作成


赤枠のボタンを押下し、アプリのニックネームを設定し「Firebase Hosting」に関して今回は未チェックでいきます
Firebase SDK の追加の設定は後で行います

Cloud Firestoreの導入

この後行う初期設定で怒られるので先に設定しておく必要があります
Cloud Firestoreは左メニューの構築から「Firestore Database」を選択する

  1. 画面中央にある「データベースを作成」を選択する
  2. 「本番環境モード」と「テストモード」の選択では「テストモード」を選択
  3. Cloud Firestore のロケーションは「asia-northeast1 (Tokyo)」を選択

デフォルトの GCP リソース ロケーションの設定


asia-northeast1を選択する

firebase 初期化

Vueプロジェクトにfirebase initで初期化を行う

firebase init


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

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

  C:\Users\shuns\OneDrive\ドキュメント\Project\vue-viviomega

# ここはYを選択しないと進まないのでYを選択
? Are you ready to proceed? (Y/n) Y

? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to
confirm your choices. (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)
>( ) Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default
instance
 ( ) Firestore: Configure security rules and indexes files for Firestore
 ( ) Functions: Configure a Cloud Functions directory and its files
 ( ) Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys
 ( ) Hosting: Set up GitHub Action deploys
 ( ) Storage: Configure a security rules file for Cloud Storage
(Move up and down to reveal more choices)

# Use an existing projectを選択
=== 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.

? Please select an option: (Use arrow keys)
> Use an existing project
  Create a new project
  Add Firebase to an existing Google Cloud Platform project
  Don't set up a default project
  
# ここはfirebase-toolsでログインしたアカウントの「firebaseでプロジェクトを作成」工程で作成したプロジェクトを選択する
? Please select an option: Use an existing project
? Select a default Firebase project for this directory: (Use arrow keys)
> vue-viviomega (vue-viviomega)

# Cloud Firestoreの導入をしておかないとここでコケます
=== Database Setup
i  database: ensuring required API firebasedatabase.googleapis.com is enabled...
!  database: missing required API firebasedatabase.googleapis.com. Enabling now...
+  database: required API firebasedatabase.googleapis.com is enabled

# Yを選択
? It seems like you haven’t initialized Realtime Database in your project yet. Do you want to set it up? (Y/n) Y

# asia-southeast1を選択
? Please choose the location for your default Realtime Database instance: (Use arrow keys)
  us-central1
  europe-west1
> asia-southeast1

Firebase Realtime Database Security Rules allow you to define how your data should be
structured and when your data can be read from and written to.

# Enterを押下
? What file should be used for Realtime Database Security Rules? (database.rules.json)

=== Firestore Setup
Firestore Security Rules allow you to define how and when to allow
requests. You can keep these rules in your project directory
and publish them with firebase deploy.

# Enterを押下
? What file should be used for Firestore Rules? (firestore.rules)

Firestore indexes allow you to perform complex queries while
maintaining performance that scales with the size of the result
set. You can keep index definitions in your project directory
and publish them with firebase deploy.

# Enterを押下
? What file should be used for Firestore indexes? (firestore.indexes.json)

# JavaScriptを選択する
? What language would you like to use to write Cloud Functions? (Use arrow keys)
> JavaScript
  TypeScript
  Python

# Noを選択
? Do you want to use ESLint to catch probable bugs and enforce style? No

# Yesを選択
+  Wrote functions/package.json
+  Wrote functions/index.js
+  Wrote functions/.gitignore
? Do you want to install dependencies with npm now? (Y/n) Y

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

# distに変更する
? What do you want to use as your public directory? (public) dist
# Nを選択
? Configure as a single-page app (rewrite all urls to /index.html)? (y/N) N
# Nを選択
? Set up automatic builds and deploys with GitHub? (y/N) N

# デフォルトの GCP リソース ロケーションの設定をしてないとここでコケる
=== Storage Setup

Firebase Storage Security Rules allow you to define how and when to allow
uploads and downloads. You can keep these rules in your project directory
and publish them with firebase deploy.

# Enterを押下
? What file should be used for Storage Rules? (storage.rules)

#取り敢えず全て選択
=== Emulators Setup
? Which Firebase emulators do you want to set up? Press Space to select emulators, then Enter to confirm your choices.
(Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)
>( ) Authentication Emulator
 (*) Functions Emulator
 ( ) Firestore Emulator
 ( ) Database Emulator
 ( ) Hosting Emulator
 ( ) Pub/Sub Emulator
 ( ) Storage Emulator
(Move up and down to reveal more choices)
# ここは特に変更なし
? Which port do you want to use for the auth emulator? 9099
? Which port do you want to use for the functions emulator? 5001
? Which port do you want to use for the firestore emulator? 8080
? Which port do you want to use for the database emulator? 9000
? Which port do you want to use for the hosting emulator? 5000
? Which port do you want to use for the pubsub emulator? 8085
? Which port do you want to use for the storage emulator? 9199
? Which port do you want to use for the eventarc emulator? 9299
? Would you like to enable the Emulator UI? Yes
? Which port do you want to use for the Emulator UI (leave empty to use any available port)?
? Would you like to download the emulators now? No

=== Remoteconfig Setup
# Enterを押下
? What file should be used for your Remote Config template? remoteconfig.template.json

=== Extensions Setup

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

+  Firebase initialization complete!

初期設定の動作テスト

エミュレータの動作チェックになります

# vueのProjectを一度ビルドする
yarn build

# 成功していれば下記内容が出力されて起動します
firebase emulators:start
┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://127.0.0.1:4000/               │
└─────────────────────────────────────────────────────────────┘

┌────────────────┬────────────────┬──────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI              │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth       │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Functions      │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions  │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Firestore      │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore  │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Database       │ 127.0.0.1:9000 │ http://127.0.0.1:4000/database   │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Hosting        │ 127.0.0.1:5000 │ n/a                              │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Pub/Sub        │ 127.0.0.1:8085 │ n/a                              │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Storage        │ 127.0.0.1:9199 │ http://127.0.0.1:4000/storage    │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Eventarc       │ 127.0.0.1:9299 │ n/a                              │
├────────────────┼────────────────┼──────────────────────────────────┤
│ Extensions     │ 127.0.0.1:5001 │ http://127.0.0.1:4000/extensions │
└────────────────┴────────────────┴──────────────────────────────────┘
  Emulator Hub running at 127.0.0.1:4400
  Other reserved ports: 4500, 9150
┌─────────────────────────┬───────────────┬─────────────────────┐
│ Extension Instance Name │ Extension Ref │ View in Emulator UI │
└─────────────────────────┴───────────────┴─────────────────────┘
Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

処理を終えるときはCtrl+Cで止まります

試しに下記URLに接続するとエミュレータのブラウザ管理画面に飛びます
http://127.0.0.1:4000/

firebase の初期化コードを追加する

Vueと連携するためにfirebaseの初期化ファイルを作成します
"src/firebase.js"というファイルをプロジェクト内に生成します
今回はエミュレータを使用した設定ファイルになります

import { initializeApp } from 'firebase/app';
import { getFunctions, connectFunctionsEmulator } from "firebase/functions";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";

import { getStorage, connectStorageEmulator } from "firebase/storage";
import { getAuth, connectAuthEmulator } from "firebase/auth";

#プロジェクトの設定画面からapiKeyを取得する
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
};
const firebase = initializeApp(firebaseConfig);
const isEmulating = window.location.hostname === "localhost";
if (isEmulating) {

    const auth = getAuth();
    connectAuthEmulator(auth, "http://localhost:9099");

    const storage = getStorage();
    connectStorageEmulator(storage, "localhost", 9199);

    const db = getFirestore(firebase);
    connectFirestoreEmulator(db, 'localhost', 8080); 

    const functions = getFunctions(firebase);
    connectFunctionsEmulator(functions, "localhost", 5001);
}

export const firebaseApp = () => { return firebase };

export default firebase;

firebaseConfigの場所


firebaseの連携しているプロジェクトの左側にあるメニュー

  1. プロジェクトの概要の右側⚙を押下
  2. プロジェクトの設定を押下
  3. SDK の設定と構成の項目のコードブロックにあります

firebase.js を .gitignore に追加

apiKeyを含んでいるので初期化コードは.gitignoreに追加する

Discussion