Nuxt.js(CompositionAPI)+TypeScriptでFirebaseと連携したい!
この記事ではNuxt.js(CompositionAPI)とTypeScriptでcreate nuxt appからfirebase連携までの流れを追っていきます。
@nuxtjs/firebaseと@nuxtjs/composition-apiを使用します。
予めインストールしておくもの
- node.js
環境
node v12.19.0
yarn 1.22.5
今回使ったコード
github: https://github.com/Ubugeeei/nuxt_ts_composition_firebase
1. create nuxt app で新規作成
まず 任意の作業ディレクトリにて npx create-nuxt-app <プロジェクト名> でプロジェクトを作成していきます。
今回は ts_fire_practice という名前で作成していきます。
yarn create nuxt-app ts_fire_practice #任意のプロジェクト名
プロジェクト名です。Enterでそのまま進みます。
? Project name: (ts_fire_practice) #そのままEnter
今回はTypeScriptを使用します。
? Programming language: (Use arrow keys)
JavaScript
> TypeScript
今回はYarnを使用します
? Package manager: (Use arrow keys)
> Yarn
Npm
しばらくデフォルトのままで進みます。
? UI framework: (Use arrow keys)
> None #Enter
Ant Design Vue
Bootstrap Vue
Buefy
・・・・・省略
? Nuxt.js modules: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>( ) Axios #Enter
( ) Progressive Web App (PWA)
( ) Content
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>( ) ESLint #Enter
( ) Prettier
( ) Lint staged files
( ) StyleLint
( ) Commitlint
? Testing framework: (Use arrow keys)
> None #Enter
Jest
AVA
WebdriverIO
今回はSPAモードで進めます。
? Rendering mode:
Universal (SSR / SSG)
> Single Page App
またしばらくデフォルトのままで
? Deployment target: (Use arrow keys)
> Server (Node.js hosting) #Enter
Static (Static/JAMStack hosting)
>( ) jsconfig.json (Recommended for VS Code if you re not using typescript) #Enter
( ) Semantic Pull Requests
( ) Dependabot (For auto-updating dependencies, GitHub only)
? What is your GitHub username? () #Enter
? Version control system: (Use arrow keys) #Enter
> Git
None
これでプロジェクトが作成されました。
プロジェクトに移動して、初期設定を行っていきます。
2. プロジェクトの初期設定
初期設定を行っていきます。
まず nuxt.config.js
を nuxt.config.ts
に改名して以下のように書き換えます。
import { NuxtConfig } from "@nuxt/types"; //追加
const config: NuxtConfig = {
//ここにexport defaultの中身をぶっこみます!
ssr: false,
head: {
title: 'ts_fire_practice',
meta: [
//=================
//-------- 省略
//=================
modules: [
],
build: {
}
}
export default config; //追加
これで nuxt.config.ts の初期設定はおしまいです!
次に、CompositionAPIの導入やfirebaseモジュールのインストールを行います。
firebaseモジュール導入
まずはターミナルで
yarn add firebase
yarn add @nuxtjs/firebase
インストールに少し時間がかかりますが、
以下のようになっていればOKです!
"dependencies": {
"@nuxtjs/firebase": "^7.5.0", // これ
"@nuxt/typescript-runtime": "^2.0.0",
"core-js": "^3.6.5",
"firebase": "^8.1.1", // これ
加えて、nuxt.config.ts
に以下を追加します。
modules: ["@nuxtjs/firebase"],
これでfirebaseがインストールできたので、次にCompositionAPIを使えるように導入していきます。
composition-api導入
ターミナルで以下を実行します。
yarn add @nuxtjs/composition-api
インストールに少し時間がかかりますが、
これも以下のようになっていればOKです!
"dependencies": {
"@nuxt/typescript-runtime": "^2.0.0",
"@nuxtjs/composition-api": "^0.14.0", //これ
"core-js": "^3.6.5",
"firebase": "^8.1.1",
加えて、nuxt.config.ts
に以下を追加します。
buildModules: [
'@nuxtjs/composition-api',
],
これでCompositioonAPIのセットアップは終わりです。
こちらのプロジェクト側での初期設定は以上となります。
これからfirebase側でプロジェクトを作成し、Nuxtと連携していきます。
3. Firebaeでプロジェクトを作成
firebaseでプロジェクトを作成していきます。
Firebase( https://console.firebase.google.com )にアクセスして、プロジェクトを作成していきます。
今回はアカウントの作成については触れませんので、予めつくったアカウントでログインしてコンソールに移動してください。
コンソールに移動したら新しいプロジェクトを作っていきます。(名前やIDは任意)
プロジェクトを作成
名前を入力し続行
続行
プロジェクトを作成
###待ちます・・・・
作成が完了したらプロジェクトをのホーム画面に行けると思うので、そこに移動して、サイドナビの歯車マーク
から プロジェクトを設定
に行きます。
そうしたら マイアプリ
のところに </>アイコン
があるのでそこをクリックします。
任意の名前を入力してアプリを作成します。
作成するとなにやらよく分からないコードが作られので一旦プロジェクトのホームに戻ります。
このコードたちは後で使います。
今回は練習として、AuthenticationをとCloud Firestoreを使っていきます。
まず、サイドナビのAuthenticationで設定を行っていきます。
始めるをクリックすると以下のようなページに行くので、
google認証を有効にしていきます。
有効にするにはメールアドレスが必要なので入力してください。
保存し、有効になっていればOKです!
続いて、Cloud Firestoreの設定です。
サイドナビのCloud Firestoreからデータベースの作成をクリックし、今回はとりあえずテストモードで作ります。
ロケーションは asia-northeast1を選択しておきます。
データベースを作成し、以下のようになれば完了です。
これでfirebaseプロジェクトの設定は完了です。いよいよNuxtとfirebaseと連携をしていきます、、、!
4.Nuxtとfirebaseを連携
ようやくここまできましたね、、
次はいよいよつなげていこうと思います。
Firebaseのコンソールに行き、サイドナビの歯車マーク
から プロジェクトを設定
に行きます。
マイアプリのCDNがあると思うので、apikey
から measurementId
までをざっとコピーします。
コピーした値をnuxt.config.ts
のmodules
に以下のように記述します。
modules: ["@nuxtjs/firebase"],
firebase: {
config: {
// ここにペースト
},
services: {
// 今回はauthとfirestoreを使うので以下のようにしておきます。
auth: true,
firestore: true
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {}
ペースト後
modules: [
[
'@nuxtjs/firebase',
{
config: {
apiKey: "ここの値は人それぞれ違います",
authDomain: "ここの値は人それぞれ違います",
databaseURL: "ここの値は人それぞれ違います",
projectId: "ここの値は人それぞれ違います",
storageBucket: "ここの値は人それぞれ違います",
messagingSenderId: "ここの値は人それぞれ違います",
appId: "ここの値は人それぞれ違います",
measurementId: "ここの値は人それぞれ違います"
},
services: {
auth: true,
firestore: true
}
}
]
],
これだけでfirebaseとの連携は終了です。簡単ですね。
5.連携の確認とCompositionAPIでのfirebaseの呼び出し方
ここまで長らくNuxt+TypeScriptとfirebaseの連携を見てきましたが、最後に実際にTSとCompositionAPIでのAuthenticationとClowd Firestoreの紐付けの確認をしてみます。
その前に。せっかくTypeScriptを導入したのでfirebaseモジュールの型を読み込んでおきましょう。
tsconfig.jsonです。
// "@nuxtjs/firebase"をtypesに追加
"types": ["@nuxt/types", "@types/node", "@nuxtjs/firebase"]
まずAuthenticationの確認から。
pages/index.vue
を書き換えます。
<template>
<div>
<h1>Nuxt.js(CompositionAPI)+TypeScriptでFirebaseと連携したい!</h1>
<h2>↓googleでログイン↓</h2>
<button @click='googleLogin'>ログイン</button>
</div>
</template>
<script lang='ts'>
import { defineComponent } from '@nuxtjs/composition-api' //coompositionを使えるように
export default defineComponent({
setup(_, { root }) {
/**
* ログイン機能
*/
const googleLogin = async () => {
try {
const provider = new root.$fireModule.auth.GoogleAuthProvider()
root.$fire.auth.signInWithRedirect(provider)
} catch (e) {
console.error(e)
}
}
return {googleLogin}
}
})
</script>
ローカルホストで確認
yarn dev
ログインボタンを押して、ログインして、Firebaseのコンソールで確認してみます。
##飛ばされる
##成功です
続いてCloud Firestore
pages/index.vue
を書き換えます。
<template>
<div>
<h1>Nuxt.js(CompositionAPI)+TypeScriptでFirebaseと連携したい!</h1>
<h2>↓googleでログイン↓</h2>
<button @click="googleLogin">ログイン</button>
<hr />
<input type="text" v-model='memo.text'/>
<button @click="addMemo">追加</button>
</div>
</template>
<script lang='ts'>
import { defineComponent reactive } from "@nuxtjs/composition-api"; //coompositionを使えるように
export default defineComponent({
setup(_, { root }) {
/**
* ログイン機能
*/
const googleLogin = async () => {
try {
const provider = new root.$fireModule.auth.GoogleAuthProvider()
root.$fire.auth.signInWithRedirect(provider)
} catch (e) {
console.error(e)
}
}
/**
* メモ機能
*/
let memo = reactive({
text: null
})
const addMemo = async () => {
try {
await root.$fire.firestore
.collection("memos")
.add({
text: memo.text
})
memo.text = null
} catch(e) {
console.error(e)
}
}
return { googleLogin, memo, addMemo }
}
})
</script>
入力フォームに入力して追加ボタンを押し、Firebaseのコンソールで確認してみます。
入力して
Firebaseのコンソールで確認できたら成功です。
今回は連携の確認のみのため、ボタンを押した後、ページには表示されませんが、Firebaseのコンソールで確認できたら連携完了です。
最後に
ここまで長々と見てきましたが、なるべく端折らずにいつ見てもわかるように記事にしてみました。
意外とググってみてもNuxt.js(CompositionAPI)+TypeScriptでFirebaseを実際に使うところまでやっているサイトがなく、初見では私もよく分からなかったのですが、なんとかいろんなサイトのつぎはぎで連携して実際に使うところまでたどり着けたので一連の流れをまとめました。
読んでいただきありがとうございました。参考になれば幸いです!
Discussion