如果您正在使用create-react app和webpack,那么您应该已经在使用nodejs firebase:
npm install --save firebase
在部署时即可实时获取配置,您需要访问此网址:
/__/firebase/init.json
所以在尝试初始化Firebase之前,您需要进行异步调用以获取存储在该位置的JSON对象。以下是一些示例代码(使用axios进行异步调用)可包含在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));
为了使这更加简化(使用npm start和dev firebase配置,并在部署时动态获取prod firebase配置),可以按照以下方式进行:
fbconfig.js:
if (process.env.NODE_ENV === "production") {
module.exports = require("./prod");
} else {
module.exports = require("./dev");
}
dev.js:
const firebaseConfig = {
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;
最后,在index.js文件中:
import getFirebaseConfig from "./fbconfig";
getFirebaseConfig.then(result => {
firebase.initializeApp(result);
...etc
)}
.catch(err => console.log(err));