How to import Firebase Firestore into a create-react-app project using ES6 syntax

一曲冷凌霜 提交于 2019-12-05 13:03:52

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

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.

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

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
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!