问题
I'm having trouble getting Firebase Firestore to work with the basic create-react-app boilerplate. Does anyone have a working sample?
The Get Started doc only explains how to set it up with require
statements, whereas I'd like to use ES6 imports.
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
What is the ES6 equivalent of require('firebase/firestore')
?
回答1:
This worked for me:
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/datastore';
From https://github.com/firebase/reactfire#using-the-firebase-js-sdk-in-react
回答2:
My trouble was that I was trying to use ES6 syntax. The Firebase docs say to access it via something like:
const firebase = require('firebase');
require('firebase/firestore');
Whereas I wanted to do something like this:
import * as Firebase from 'firebase';
import Firestore from 'firebase/firestore';
That didn't seem to work, but this does:
import * as Firebase from 'firebase';
require('firebase/firestore');
I don't like mixing import
and require
, but good enough for now.
回答3:
Two months later, this is working for me:
import * as firebase from 'firebase';
import '@firebase/firestore';
(It also works without the '@'.)
Here's the dependencies section from my package.json:
{
...
"dependencies": {
"@firebase/app": "^0.2.0",
"@firebase/firestore": "^0.4.1",
"firebase": "^4.13.1",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.4"
},
...
}
I started out following the instructions on npmjs.com for the firebase package. In its dependencies, I found @firebase/firestore, and tried to follow those instructions, which say to import like this:
import firebase from '@firebase/app';
import '@firebase/firestore'
However, this method of importing firebase didn't work for me -- I was able to initialize my app, but trying to execute firebase.auth().signInWithPopup(provider)
caused an error:
TypeError: WEBPACK_IMPORTED_MODULE_0__firebase_app.default.auth is not a function
回答4:
I created a config file for firebase:
import * as firebase from 'firebase';
const config = { /* COPY THE ACTUAL CONFIG FROM FIREBASE CONSOLE */
apiKey: "apiKey",
authDomain: "domen.firebaseapp.com",
databaseURL: "https://domen.firebaseio.com",
projectId: "lavs-mercury",
storageBucket: "",
messagingSenderId: "id"
};
export default firebase.initializeApp(config);
Then I just import this module to file where I want to use. For example:
import * as actionTypes from './actionTypes';
import firebase from "../../firebase-module";
export const logout = () => {
firebase.auth().signOut();
return {
type: actionTypes.LOGOUT
}
};
来源:https://stackoverflow.com/questions/48978232/how-to-import-firebase-firestore-into-a-create-react-app-project-using-es6-synta