在尝试初始化 CloudFirestore 时,firebase.firestor()不是一个函数

当我尝试初始化 Firebase Cloud Firest 时,我遇到了以下错误:

未捕获的 TypeError: MODULE _ 0 _ firebase.firest 不是一个函数

我以前用 npm install firebase --save安装过火源。

import * as firebase from 'firebase';
import router from '../router';


const config = {
apiKey: "a",
authDomain: "a",
databaseURL: "a",
projectId: "a",
storageBucket: "a",
messagingSenderId: "a"
};
if(!firebase.apps.length){
firebase.initializeApp(config);
let firestore = firebase.firestore();
}
131736 次浏览

To use Firestore cloud functions on Node.js you should use admin.firestore() instead of admin.database(). Also you should be sure that your module firebase-admin on package.json is up to 5.4.1 or above. Looking like something like:

{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"firebase-admin": "^5.4.1",
"firebase-functions": "^0.7.0"
}
}

First, make sure you have latest version of firebase:

npm install firebase@4.12.0 --save

Next, add both firebase and firestore:

const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");

Initialize the firebase app:

firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});


// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();

source: https://firebase.google.com/docs/firestore/quickstart?authuser=0

If by any chance, your code is under witchcraft, and import firebase/firestore won't work, then include it directly:

import '@firebase/firestore/dist/esm/index';

If it's not there, then:

npm install @firebase/firestore

I think I've got it for folks using electron-webpack. Solution was from a post related to importing codemirror. https://github.com/electron-userland/electron-webpack/issues/81

This worked for me.

// package.json
{
//...
"electronWebpack": {
"whiteListedModules": [
"firebase"
]
},
//...
}

I fixed it by importing multiple libraries: firebase and firebase/firestore. That's because the firebase core library does not include the firestore library.

import firebase from 'firebase/app';
import 'firebase/firestore';
import { firebase } from '@firebase/app';
import '@firebase/firestore'

If you're using authentication as well

import '@firebase/auth';

I had same Error and tried to follow the official website but did not work. Then I googled error and landed in this post.

I tried:

import * as firebase from 'firebase';
import 'firebase/firestore';

However, it did not work for me but I added /firebase to the first line import * as firebase from 'firebase/firebase'; and everything is working perfectly.

It also works with require:

const firebase = require("firebase/firebase");
// Required for side-effects
require("firebase/firestore");

If you are updating from an earlier version of firebase and you are pulling your hair out about this issue, try const Firebase = require('firebase/firebase') instead of require('firebase/app')

If you're like me and like everything typed on typescript (it's the purpose, by the way), you can try:

import * as firebase from "nativescript-plugin-firebase";
import { User, firestore } from "nativescript-plugin-firebase";


import * as firebaseapp from "nativescript-plugin-firebase/app";

So you can do stuff like that:

firebase.getCurrentUser().then((user: User) => { /* something */ });


const mycollection : firestore.CollectionReference = firebaseapp.firestore().collection("mycollection");

Removing node_modules directory together with package-lock.json and then running npm install fixed it for me.

https://github.com/angular/angularfire2/issues/1880

Hope this helps to someone who faces the same problem when deploying an Angular app to Firestore.

In Angular 8 project, I had the same error when deploying to Firestore. I fixed it by adding another module AngularFirestoreModule.

App.module.ts is like this:

...
import { AngularFireModule } from '@angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '@angular/fire/firestore'; // << Note AngularFirestoreModule !!!
import { AngularFireDatabaseModule } from '@angular/fire/database';
...


imports: [
BrowserModule,
FormsModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireDatabaseModule,
...

package.json:

...
"dependencies": {
"@angular/animations": "~8.2.2",
"@angular/common": "~8.2.2",
"@angular/compiler": "~8.2.2",
"@angular/core": "~8.2.2",
"@angular/fire": "^5.2.1",
"@angular/forms": "~8.2.2",
"@angular/platform-browser": "~8.2.2",
"@angular/platform-browser-dynamic": "~8.2.2",
"@angular/router": "~8.2.2",
"ajv": "^6.10.2",
"bootstrap-scss": "^4.3.1",
"core-js": "^2.5.4",
"firebase": "^6.4.0",
...

UPDATE: When I deployed to some other hosting provider, this did not help. For this case, I added the original firebase library and it worked.

import { firestore } from 'firebase';

To use firestore you need to add this link at the top of your html page.

//After initializing firebase, in your main javascript page call...
var data = firebase.firestore();
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-storage.js"></script>

In my case the problem was that I've accidentally added firebase-admin alongside with the firebase package in my package.json. And firebase-admin took precedence so even after adding the imports as per the accepted answer I was still getting the same error.

Removing the redundant firebase-admin from the client app fixed the problem.

As a note, firebase-admin is intended for server side to operate in admin mode, while the firebase package is a client side library.

Solution for Angular 8 (as of 4th January 2020):

  1. Delete package-lock.json file
  2. Run npm install
  3. import AngularFirestoreModule from @angular/fire/firestore

Just need to import AngularFirestoreModule.

// App.module.ts


import { AngularFireModule } from '@angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireDatabaseModule } from '@angular/fire/database';
imports: [
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireDatabaseModule
]

I used to have the same problem, it was a bug. I was importing firestore from firebase (it was done automatically by the IDE...) when i should imported it from the .js file where i initialized firebase app.

I am using the latest version of Angular 8.2.14, when I deployed to production, it cause this problem, so I add the following to app.module.ts

        imports: [
...,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireDatabaseModule,
...
],
providers: [AngularFirestore, AngularFirestoreModule],

I found a useful comment in Github by alclimb

he mentioned about firebase analytics won't work in Node.js, because it meant to be used with a browser (this is mention in the official documentation)

You can create a separate component for initialization of firebase on you application using credentials.

firebase-context.js

import * as firebase from 'firebase'
import 'firebase/firestore';


const firebaseConfig = {
apiKey: "XXXX",
authDomain: "XXXXX.firebaseapp.com",
databaseURL: "https://XXXX-app-web.firebaseio.com",
projectId: "XXXX",
storageBucket: "XXXX-app-web.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXX:web:XXXX",
measurementId: "G-XXXX"
};


export default !firebase.apps.length
? firebase.initializeApp(firebaseConfig).firestore()
: firebase.app().firestore();

In case, you need to deal with database operation you don't need to call the initialize method each time, you can use common component method which is earlier created.

import FirebaseContext from "./firebase-context";


export const getList = () => dispatch => {
FirebaseContext.collection("Account")
.get()
.then(querySnapshot => {
// success code
}).catch(err => {
// error code
});
}

Enabling Firestore for Nativescript

During plugin installation you'll be asked whether or not you use Firestore.

In case you're upgrading and you have the firebase.nativescript.json file in your project root, edit it and add: "firestore": true. Then run rm -rf platforms && rm -rf node_modules && npm i.

init / initializeApp

By default Firestore on iOS and Android persists data locally for offline usage (web doesn't by default, and the regular Firebase DB doesn't either on any platform). If you don't like that awesome feature, you can pass persist: false to the init function.

Note that initializeApp is simply an alias for init to make the plugin compatible with the web API.

const firebase = require("nativescript-plugin-firebase/app");


firebase.initializeApp({
persist: false
});

collection

A 'collection' is at the root of any Firestore interaction. Data is stored as a 'document' inside a collection.

 const citiesCollection = firebase.firestore().collection("cities");

Source: nativescript-plugin-firebase

The problem is not import the firestore

firebase has many features.

You need to import or import from the CDN what you want to implement from the list below.

enter image description here The official reference says to load firebase-firestore.js.

<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-firestore.js"></script>

if you want to use npm, here

npm install firebase@7.19.0 --save

url is here
https://firebase.google.com/docs/firestore/quickstart?authuser=0#set_up_your_development_environment

In vanilla javascript on the client you need to include this script to make it work:

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>

as it's not included in the default snippet Google asks you to copy paste in your website.

Source: https://firebase.google.com/docs/firestore/quickstart?authuser=0

simply the answer is just to link these script in your html file and check that the issue is resolved

script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"

script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js

gives upvote if it is helpful for fixing your problem

In my case, the error was because I tried to import a file that used firebase.firestore() before I actually imported "firebase/firestore"

I also struggled with this for a bit. what I did in the end was quite straightforward.

for versions 9 and higher, just do the following

import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';


// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries


// Your web app's Firebase configuration
const firebaseConfig = {
apiKey:
authDomain:
projectId:
storageBucket:
messagingSenderId:
appId:
};


// Initialize Firebase


const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore;
const auth = firebaseApp.auth();




export { auth };
export default db;


//cheers

If you are using the version the version 9 of firebase, then you need to use this instead:

// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';

Here is the link for the upgrade from version 8 to version 9 https://firebase.google.com/docs/web/modular-upgrade

For 2022 readers, please check your firebase version.

The latest version now is 9.x. It is little different from mostly YouTube guides.

You need firebase@8.x to follow YouTube guides.

npm uninstall firebase

npm install firebase@8.x

Docs: https://firebase.google.com/docs/firestore/quickstart?authuser=0#web-version-9_1

import { getFirestore } from "firebase/firestore";

Just try this and see how it goes

For version 9 of firebase you can use

import firebase from 'firebase/compat/app';
import "firebase/compat/firestore";

For me, the issue came from using the wrong import. I create the firebase app elsewhere in my code with initializeApp. This is a server side node.js app. Firebase Admin cannot be used in the client anyway.

Incorrect

import admin from 'firebase-admin';


this.stripeAccountColl = admin.firestore(this.firebaseApp).collection("StripeAccount");

Correct

import { getFirestore } from 'firebase-admin/firestore';


this.stripeAccountColl = getFirestore(this.firebaseApp).collection("StripeAccount");