LoginSignup
0
0

More than 1 year has passed since last update.

Astro製WebサイトにFirebase Analyticsを導入する

Last updated at Posted at 2023-03-23

はじめに

本稿では、Astroを使って生成されたWebサイトにFirebase Analyticsを導入する方法を紹介します。

Astroとは、コンテンツにフォーカスした高速なWebサイトを構築するためのフレームワークで、Static Site Generator (SSG: 静的サイトジェネレータ)の一つです。Astroの詳細はここでは割愛します。

本稿を読むにあたり前提として、Astroプロジェクトの作成、Firebaseプロジェクトの作成およびAnalyticsの有効化は既に完了しているものとします。

Astro v2系、Firebase v9 SDKを使用します

Firebase JavaScriptライブラリの追加

下記コマンドでAstroプロジェクトにFirebaseライブラリを追加します。

yarn add firebase
# npmの場合は npm install firebase

Firebaseコンポーネントの作成

Firebase.astroファイルをAstroプロジェクトのsrc/componentsディレクトリ配下に追加します。

このファイルには、 <script> タグを追加して以下のようなJavaScriptを追記します。このJavaScriptは、Analyticsを有効化したときに表示されたスクリプトをそのままコピペするで構いません。(このスクリプトはFirebaseのプロジェクトの設定で確認することができます)

src/components/Firebase.astro
<script>
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "firebase/app";
    import { getAnalytics } from "firebase/analytics";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
        apiKey: "Your Api Key",
        authDomain: "Your Auth Domain",
        projectId: "Your Project Id",
        storageBucket: "Your Storage Bucket",
        messagingSenderId: "Your Messaging Sender Id",
        appId: "Your App Id",
        measurementId: "Your Measurement Id"
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
</script>

.astro ファイルに <script> タグを追加することで、クライアントサイドJavaScriptを追加することができます。
import { initializeApp } from "firebase/app" のようにNodeモジュールをインポートすることができ、すべてバンドルされた上で <head> に.jsファイルが挿入されます。

【参考】 https://docs.astro.build/en/guides/client-side-scripts/

Firebaseコンポーネントの利用

上記で作成したFirebase.astroをアナリティクスを使いたいページに挿入します。
本稿の例では、全ページにアナリティクスを効かせたいので、Layout.astro (全ページ共通のガワコンポーネント)に <Firebase/> コンポーネントを挿入しています。

src/layouts/Layout.astro
---
import Firebase from '../components/Firebase.astro';

---

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Something -->
</head>

<body>
  <!-- Firebase Analyticsの利用 -->
  <Firebase/>
  <!-- 各ページのコンテンツを挿入 -->
  <slot/>
</body>
</html>

以上でAstro製WebサイトにFirebase Analyticsを導入することができました。

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