0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue3+Firebaseでアプリをつくる①環境構築

Last updated at Posted at 2024-09-01

はじめに

前回書籍を片手にVueでTODOアプリを作成しました。

今回は、バックエンドにFirebaseを使用してWebアプリケーションを構築していきます。
本記事では、環境構築に焦点を当て、以下の内容を扱います:

  1. Vueプロジェクトの作成
  2. Firebaseプロジェクトの作成
  3. VueとFirebaseの連携
  4. プロジェクトのビルドとデプロイ

0.開発環境

OS:Windows 11 Home 23H2
エディタ:VSCode
Node.js:v20.16.0
npm:10.8.1

1. Vueプロジェクトの作成

1-1. プロジェクトを作成したいフォルダに移動します

1-2. コマンドを実行してVueプロジェクトを作成します

Vueプロジェクトの作成
> npm create vue@latest

vue@latestでプロジェクトを作るのは公式で推奨されている1ようですが、このブログを書いている現在ではほとんどサンプルがないです。でもどうせ勉強なんだからということでこのまま突き進みます。

1-3. Vueプロジェクトを作成する

プロジェクト名はmy-vue3-booklendingにしました。オプションは次の画像の通りです。
※ネット情報はJSが多かったので、TypeScriptは入れませんでした。Routerを使うのでYes、あとは前回と同じ。

image.png

1-4. プロジェクトフォルダに移動し、必要なパッケージをインストールします

firebaseのインストール
> cd my-vue3-booklending
> npm install 
> npm run format
> npm run dev

1-5. VITEで起動することを確認する

2.Firebaseプロジェクトの作成

2-1. Firebase公式サイトにアクセスしてFirebaseプロジェクトの作成を行う

2-2. プランを選択する

今回は無料のSparkプランを使います。
これ以降の手順はSparkプランになります。
image.png

2-3. プロジェクトを作成する

今回はmy-firebase-booklendingでプロジェクトを作成します。
image.png

image.png

Googleアナリティクスの設定については、とりあえず「あり」で設定しました。
※今後の実装で失念する可能性あり。

image.png

image.png

image.png

image.png

プロジェクトができました。

2-4. ウェブアプリを作成する

ウェブアプリをクリックして機能を追加する。
アプリのニックネームはbooklendingで、Firebase Hostingも設定します。

image.png

image.png

ここで表示される設定情報はアプリ側で設定するのでコピーしてどこかにおいておくことを推奨します。
※いつでもFirebaseコンソールから確認可能です。

image.png

3.VueとFirebaseの連携

3-1. 環境変数の設定

先ほどの設定を安全に管理するためにプロジェクトのルートディレクトリに.envファイルを作成して、Firebaseの設定情報を記入します。

(pj-root)/.env
VITE_API_KEY="Firebaseでアプリ登録したときのapiKey"
VITE_AUTH_DOMAIN="Firebaseでアプリ登録したときのauthDomain"
VITE_PROJECT_ID="Firebaseでアプリ登録したときのprojectId"
VITE_STORAGE_BUCKET="Firebaseでアプリ登録したときのstorageBucket"
VITE_MESSAGING_SENDER_ID="Firebaseでアプリ登録したときのmessagingSenderId"
VITE_APP_ID="Firebaseでアプリ登録したときのappId"
VITE_MEASUREMENT_ID="Firebaseでアプリ登録したときのmeasurementId"

Githubを使っている場合、API_KEYなどが公開されてしまわないよう.gitignoreにenvを追加する。

(pj-root)/.gitignoreに追加
# Environment
/.env

3-2. Firebaseモジュールをインストールする

プロジェクトのルートディレクトリで以下のコマンドを実行してFirebaaseモジュールをインストールする。

Firebaseモジュールのインストール
> npm install firebase --save

3-3. Firebase初期化ファイルを作成する

scr直下にfirebaseフォルダを作成してinit.jsを作成します。

(pj-root)/scr/firebase/init.js
import { initializeApp } from 'firebase/app'
import { getAnalytics } from 'firebase/analytics'

const firebaseConfig = {
  // envから取得
  apiKey: import.meta.env.VITE_API_KEY,
  authDomain: import.meta.env.VITE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_PROJECT_ID,
  storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_APP_ID,
  measurementId: import.meta.env.VITE_MEASUREMENT_ID
}

// Initialize Firebase
const app = initializeApp(firebaseConfig)
const analytics = getAnalytics(app)

export { analytics }

先ほどの.envファイルを読み込んでいます。

3-4. initファイルを読み込む

とりあえずmain.jsでinit.jsを読み込む

(jp-root)/src/main.js
import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './firebase/init' // 追加

const app = createApp(App)

app.use(router)

app.mount('#app')

4.プロジェクトのビルドとデプロイ

4-1.プロジェクトのビルド

プロジェクトのルートディレクトリで以下のコマンドを実行してビルドします。

プロジェクトのビルド
> npm run build

これにより、distディレクトリにビルドされたファイルが生成されます。

4-2. Firebase CLIのインストール

Firebase CLIをインストールして、ログインする。

Firebase CLIのインストール&ログイン
> npm install -g firebase-tools

> rem Firebaseにログインする(Googleアカウント)
> firebase login

4-3. Firebaseプロジェクトを初期化する

Firebase 初期化
> firebase init
参考
     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

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

  (root-directory)\my-vue3-booklending

? Are you ready to proceed? Yes
? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to
confirm your choices. Firestore: Configure security rules and indexes files for Firestore, Hosting: Configure
files for Firebase Hosting and (optionally) set up GitHub Action deploys

=== 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 an existing project
? Select a default Firebase project for this directory: my-firebase-booklending
i  Using project my-firebase-booklending

=== 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.

? 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.

? What file should be used for Firestore indexes? firestore.indexes.json

=== 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.

? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? Set up automatic builds and deploys with GitHub? No
+  Wrote public/index.html

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

+  Firebase initialization complete!

4-4. Hostingのリダイレクト先を設定する

firebase.jsonファイルを開き、以下のように設定を更新します:

firebase.json
{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

この設定により、distディレクトリがデプロイ対象となり、
ルートがindex.htmlにリダイレクトされます。

4-5. プロジェクトをデプロイする

> firebase deploy
参考
=== Deploying to 'my-firebase-booklending'...

i  deploying firestore, hosting
i  firestore: reading indexes from firestore.indexes.json...
i  cloud.firestore: checking firestore.rules for compilation errors...
+  cloud.firestore: rules file firestore.rules compiled successfully
i  firestore: deploying indexes...
+  firestore: deployed indexes in firestore.indexes.json successfully for (default) database
i  firestore: latest version of firestore.rules already up to date, skipping upload...
i  hosting[my-firebase-booklending]: beginning deploy...
i  hosting[my-firebase-booklending]: found 6 files in dist
+  hosting[my-firebase-booklending]: file upload complete
+  firestore: released rules firestore.rules to cloud.firestore
i  hosting[my-firebase-booklending]: finalizing version...
+  hosting[my-firebase-booklending]: version finalized
i  hosting[my-firebase-booklending]: releasing new version...
+  hosting[my-firebase-booklending]: release complete

+  Deploy complete!

デプロイが完了したら、表示されたHosting URLにアクセスして、Vueの初期画面が表示されることを確認します。

image.png

これで環境構築は完了です。次回は、この環境を使ってアプリケーションの機能を実装していきます。

おわりに

おわりに、というか免責事項に近いのですが・・・
VueもFirebaseもほぼ初めてなのでここまで構築するのに、正直プロジェクトを何度作り直してトライ&エラーしたのかわかりません!
なので、この通り進めて「できひんやんけ!」となった場合は、あきらめてトライ&エラーを楽しみましょう!

  1. https://ja.vuejs.org/guide/quick-start#creating-a-vue-application

0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?