LoginSignup
5
4

More than 3 years have passed since last update.

nuxt.js + Firebaseでアプリを作る際に `import firebase ~~ `を毎回書きたくない

Last updated at Posted at 2020-01-17

前提

nuxt.js + Firebaseでアプリを開発していると、Firebase操作が必要な各ページで
import firebase from '~/plugins/firebase'
の記述が必要ということに気づきました。
ページ数が多いわけではないですが、
Auth処理とFirestore操作でほぼ全ページに必要だったので、書かなくて済む方法はないかと思った次第です。

今のところこのやり方でうまく行ったようなので、備忘録として残しておきます。

結論

関数のinjectと同様にすればよいっぽい。

plugins/firebase.js
import firebase from 'firebase'

if (!firebase.apps.length) {
  firebase.initializeApp({
    apiKey: process.env.API_KEY,
    authDomain: process.env.AUTH_DOMAIN,
    databaseURL: process.env.DATABASE_URL,
    projectId: process.env.PROJECT_ID,
    storageBucket: process.env.STORAGE_BUCKET,
    messagingSenderId: process.env.MESSAGING_SENDER_ID
  })
}

// いつもはこのやり方
// export default firebase

// injectに変更する
export default ({ app }, inject) => {
  inject('firebase', firebase)
}
nuxt.config.js
export default {
  plugins: ['~/plugins/firebase.js']
}

使用例

pages/index.js
<script>
// 不要 => import firebase from '~/plugins/firebase'

export default {
  methods: {
    login() {
      this.$firebase  // いつもの firebase が this.$firebase で呼び出せる
        .auth()
        .signInWithRedirect(new this.$firebase.auth.GoogleAuthProvider())
    },
  }
}
</script>

最後に

プラグイン - NuxtJS

nuxt.jsのリファレンスにある「統合された注入」というものを使っていますが正直あまりよくわかっていないです。
間違っていることやそうしてはNGな理由などがあれば是非コメントで教えてください。

5
4
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
5
4