Resolving Firebase Module (React-Native)

Error: While trying to resolve module `firebase` from file `/Users/---i/Desktop/mapnav/database/firebase.js`, the package `/Users/---/Desktop/mapnav/node_modules/firebase/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/---/Desktop/mapnav/node_modules/firebase/index`. Indeed, none of these files exist:


  * /Users/--/Desktop/mapnav/node_modules/firebase/index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)

I’m trying to access the Firebase authentication services via its API; However I keep getting the error above and I’m not able to use firebase within the app. I’m using the web firebase SDK; and trying to call the api in my Login.js file in order to authenticate logins. The tutorial I was following they initialised it like this: firebase.initializeApp(firebaseConfig); and exported it and called it wherever they needed however again resulted in the same error.

Firebase File:

import * as firebase from 'firebase';



// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// 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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
export const firebaseConfig = {
  apiKey: "AIzaSyB4B2S4hYhtifD9QyM39B9U6Ms7uOKQMQU",
  authDomain: "reactnativefb-15348.firebaseapp.com",
  projectId: "reactnativefb-15348",
  storageBucket: "reactnativefb-15348.appspot.com",
  messagingSenderId: "188069430669",
  appId: "1:177069430799:web:1c6a08c65cfe3bb7a5057a",
  measurementId: "G-0WKYCHFZWK"
};

// Initialize Firebase
// export const app = initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
firebase.initializeApp(firebaseConfig);
export default firebase;

Login Js:

import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
// import { firebase } from '@react-native-firebase/auth';
import firebase from './database/firebase';

export default class Login extends Component {
  
  constructor() {
    super();
    this.state = { 
      email: '', 
      password: '',
      isLoading: false
    }
  }

  updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val;
    this.setState(state);
  }

  userLogin = () => {
    if(this.state.email === '' && this.state.password === '') {
      Alert.alert('Enter details to signin!')
    } else {
      this.setState({
        isLoading: true,
      })
      firebase
      .auth()
      .signInWithEmailAndPassword(this.state.email, this.state.password)
      .then((res) => {
        console.log(res)
        console.log('User logged-in successfully!')
        this.setState({
          isLoading: false,
          email: '', 
          password: ''
        })
        this.props.navigation.navigate('Dashboard')
      })
      .catch(error => this.setState({ errorMessage: error.message }))
    }
  }

  render() {
    if(this.state.isLoading){
      return(
        <View style={styles.preloader}>
          <ActivityIndicator size="large" color="#9E9E9E"/>
        </View>
      )
    }    
    return (
      <View style={styles.container}>  
        <TextInput
          style={styles.inputStyle}
          placeholder="Email"
          value={this.state.email}
          onChangeText={(val) => this.updateInputVal(val, 'email')}
        />
        <TextInput
          style={styles.inputStyle}
          placeholder="Password"
          value={this.state.password}
          onChangeText={(val) => this.updateInputVal(val, 'password')}
          maxLength={15}
          secureTextEntry={true}
        />   
        <Button
          color="#3740FE"
          title="Signin"
          onPress={() => this.userLogin()}
        />   

        <Text 
          style={styles.loginText}
          onPress={() => this.props.navigation.navigate('Signup')}>
          Don't have account? Click here to signup
        </Text>                          
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    padding: 35,
    backgroundColor: '#fff'
  },
  inputStyle: {
    width: '100%',
    marginBottom: 15,
    paddingBottom: 15,
    alignSelf: "center",
    borderColor: "#ccc",
    borderBottomWidth: 1
  },
  loginText: {
    color: '#3740FE',
    marginTop: 25,
    textAlign: 'center'
  },
  preloader: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: 'absolute',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff'
  }
});

Json:

Answer

You are using the new modular SDK (v9.0.0) so you can no longer have the following import:

import firebase from "firebase"

If you want to use the old namespaced syntax then you would have to use compat libraries:

import firebase from "firebase/compat/app"

In your Firebase file you are mixing both the syntaxes. First remove the import from the top, initialize Firebase without the namespace and export relevant services:

// firebase.js

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {...}

const app = initializeApp(app)
const auth = getAuth(app)

export {auth}

Now you can import authentication in your other components:

import {auth} from "../path/to/firebase.js"
import {signInWithEmailAndPassword} from "firebase/auth"


// use the imported methods
signInWithEmailAndPassword(auth, "email", "password").then(() => {
  //...
})

// This is older name-spaced version
// firebase.auth().signInWithEmailAndPassword()...

Make sure your paths referencing to import are correct.