LoginSignup
1
0

More than 5 years have passed since last update.

`react-scripts start` で起動したときに Firebase の JavaScript SDK を使用できるようにする

Last updated at Posted at 2018-02-15

Firebase Hosting用のアプリを作る際に、firebase init hostingってコマンドを実行するといろいろファイルが生成されるのですが、index.htmlを見てみると以下のように /__/ ってパスが入っています。

<script defer src="/__/firebase/4.9.1/firebase-app.js"></script>

ローカルで開発する際にはこのファイルは実際には存在していなくて、firebase serve というコマンドでローカルサーバーを起動するといい感じで解決してくれるのですが、Reactベースのアプリをcreate-react-appで作ったときには、react-scripts startでローカルサーバーを起動したほうが便利で、いやーんってなったのでその解決方法。

Firebase の JavaScript SDK をインストール

$ npm install firebase --save

App.jsを修正

App.jsに以下の行を追加。

import firebase from 'firebase';
import { firebaseConfig } from './firebase-config.js';

firebase.initializeApp(firebaseConfig);

次にFirebaseの設定ファイルを src/firebase-config.js に作成。

ファイルの内容は Firebase のダッシュボードで入手できます。

だいたい以下のような感じ。

export const firebaseConfig = {
  apiKey: "xxxx,
  authDomain: "xxxx",
  databaseURL: "xxxx",
  projectId: "xxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxx"
};

設定ファイルを設置

プロジェクトのルートディレクトリに firebase.json というファイル名で以下の内容を保存。

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

.firebasercというファイルを作る。内容は空のオブジェクト。

{}

起動

以上で create-react-app で生成された package.json に記述された npm start で起動します。

$ npm start

あとは React のお作法に従ってゴリゴリ頑張る。

1
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
1
0