🙄

firebase.js

2022/12/26に公開

Nuxtでfirebaseの各種サービスに接続するためのインスタンスを生成するプラグイン。
nuxt.config.jsのpublicRuntimeConfigを使用して環境変数を読み込む。
環境変数の切り替えにはcross-envを利用して、実行するscriptのコマンドで切り替えることも可能。

/**
 * firebase.js
 * Copyright 2022 shisyamo4131. All Rights reserved.
 *
 * Initialize firebase app and inject instances of firebase services to Nuxt.
 * You can use each instances as '$serviece-name'.
 *
 * API keys are configured in .env files and read in nuxt.config.js.
 * ex.)
 * .env.dev for development.
 * .env.prod for production.
 * By configuring "useEmulator(boolean)", it is possible to switch the connection to firebase emulators.
 * Learn more about publicRuntimeConfig.
 * https://nuxtjs.org/docs/directory-structure/nuxt-config#runtimeconfig
 *
 * 1. Install cross-env to your project.
 *    npm i cross-env
 *
 * 2. Create .env.dev.js and .env.prod.js at root directory.
 *    Configure API keys in each file. Do not forget configuring 'useEmulator'.
 *
 * 3. Add 'publicRuntimeConfig' to nuxt.config.js
 *
 * 4. Edit package.json's scripts.
 *    ex.)
 *    "dev": "cross-env NUXT_HOST=0.0.0.0 NUXT_PORT=3000 NODE_ENV=\"dev\" nuxt",
 */
import { initializeApp } from 'firebase/app'
import { connectFirestoreEmulator, getFirestore } from 'firebase/firestore'
import { connectDatabaseEmulator, getDatabase } from 'firebase/database'
import { connectAuthEmulator, getAuth } from 'firebase/auth'
import { connectFunctionsEmulator, getFunctions } from 'firebase/functions'
import { connectStorageEmulator, getStorage } from 'firebase/storage'

export default (context, inject) => {
  const firebaseConfig = {
    apiKey: context.$config.apiKey,
    authDomain: context.$config.authDomain,
    databaseURL: context.$config.databaseURL,
    projectId: context.$config.projectId,
    storageBucket: context.$config.storageBucket,
    messagingSenderId: context.$config.messagingSenderId,
    appId: context.$config.appId,
  }
  const firebaseApp = initializeApp(firebaseConfig)
  const inAuth = getAuth(firebaseApp)
  const inFunctions = getFunctions(firebaseApp)
  const inFirestore = getFirestore(firebaseApp)
  const inDatabase = getDatabase(firebaseApp)
  const inStorage = getStorage(firebaseApp)

  if (context.$config.useEmulator) {
    connectAuthEmulator(inAuth, 'http://localhost:9099')
    connectFunctionsEmulator(inFunctions, 'localhost', 5001)
    connectFirestoreEmulator(inFirestore, 'localhost', 8080)
    connectDatabaseEmulator(inDatabase, 'localhost', 9000)
    connectStorageEmulator(inStorage, 'localhost', 9199)
  }

  inject('auth', inAuth)
  inject('functions', inFunctions)
  inject('firestore', inFirestore)
  inject('database', inDatabase)
  inject('storage', inStorage)
}

Discussion