简体   繁体   中英

Using Firebase with React in Firebase Hosting

I'm developing a React app created with "create react app" ( https://github.com/facebookincubator/create-react-app ). It will be hosted in Firebase Hosting and I'll like to use implicit initialization as describe in documentation ( https://firebase.google.com/docs/web/setup#sdk_imports_and_implicit_initialization ), to deploy to multiple projects (I have a dev project and several production projects)

<script src="/__/firebase/init.js"></script>

I need to get the "firebase" object initialized in the script above in my React components. How should I import it in multiple React components files? I'm aware that this will be only available when I serve it with "firebase serve" during development and when I deploy it, so during development I'm trying to add

<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase.js"></script>
<script>
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>",
  };
  firebase.initializeApp(config);
</script>

code to my index.html file as describe in Firebase docs. However, when I try to import Firebase in ReactComponent it doesn't find it or complains about not initialize project (what I'm doing in the html tag)

How do I import Firebase initialized App and Firebase libraries from my html script tags??

As you are using create-react app and thus webpack, you should already be using nodejs firebase:

npm install --save firebase

To get the config on the fly when deployed, you have to access this url:

/__/firebase/init.json

So you need to make an async call to get the json object stored on this location, before you try to initiliaze firebase. So here is some sample code (using axios for the async call) to include in your index.js:

    import React from "react";
    import ReactDOM from "react-dom";
    import * as firebase from "firebase/app";
    import axios from "axios";

    const getFirebaseConfig = new Promise((resolve, reject) => {
      axios
        .get(`/__/firebase/init.json`)
        .then(res => {
          resolve(res.data);
        })
        .catch(err => reject(err));
    });

    getFirebaseConfig
      .then(result => {
        firebase.initializeApp(result);

        ReactDOM.render(
          <div>XXXXX</div>,
          document.getElementById("root")
        );
      })
      .catch(err => console.log(err));

Also in order to make this more streamlined (use dev firebase config with npm start, and get prod firebase configurations on the fly if deployed) you can do something like the below:

fbconfig.js:

if (process.env.NODE_ENV === "production") {
  module.exports = require("./prod");
} else {
  module.exports = require("./dev");
}

dev.js:

const firebaseConfig = {
  // your dev firebase configuration
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxxxx",
  projectId: "xxxxxx",
  storageBucket: "xxxxx",
  messagingSenderId: "xxxxx"
};

const getFirebaseConfig = new Promise((resolve, reject) => {
  resolve(firebaseConfig);
});

export default getFirebaseConfig;

prod.js:

import axios from "axios";

const getFirebaseConfig = new Promise((resolve, reject) => {
  axios
    .get(`/__/firebase/init.json`)
    .then(res => {
      resolve(res.data);
    })
    .catch(err => reject(err));
});

export default getFirebaseConfig;

And finally in index.js:

import getFirebaseConfig from "./fbconfig";

getFirebaseConfig.then(result => {
  firebase.initializeApp(result);
  ...etc
)}
.catch(err => console.log(err));

You're providing the firebase API directly in the browser with a script tag. It's already going to be available in the browser when you run your bundle.

You're using webpack behind the scenes with create-react-app , but I think you might need to eject it so you can tell it that this package is going to be available on your environment (browser) using the externals property.

https://webpack.js.org/configuration/externals/

From what I understand from this issue, it's not possible to add externals to webpack using create-react-app .

https://github.com/facebook/create-react-app/issues/780

Maybe it's best to drop the <script> tag with the firebase and just install and import it directly on your CRA project.

This might help: https://www.codementor.io/yurio/all-you-need-is-react-firebase-4v7g9p4kf

Just try to install firebase package via npm. Then you can easily use it wherever you want in any react component by importing with

import firebase from 'firebase';

You can also import firebase in some configureFirebase.js file where you can initialize firebase app with some configs, then export configured firebase instance and use this instance in any component

Its would be helpful:

import firebase from 'firebase'
const config = { /* COPY THE ACTUAL CONFIG FROM FIREBASE CONSOLE */
    apiKey: "unreadablestuff",
    authDomain: "your-domain-name.firebaseapp.com",
    databaseURL: "https://your-domain-name.firebaseio.com",
    storageBucket: "your-domain-name.appspot.com",
    messagingSenderId: "123123123123"
};
const fire = firebase.initializeApp(config);
export default fire;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM