'firebase package was successfully found. this package itself specifies a `main` module field that could not be resolved. none of these files exist

node_modules\firebase\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved node_modules\firebase\index`. Indeed, none of these files exist

I have made this code, but i am dealing with this constant error. can someone help me? currently the issue is with firebase, and I am no expert here. I have tried doing a few things, but they are not working. if tried adding compat to firebase libraries but the error has still not been resolved. If anyone else has ever experienced this issue before, please help.

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Generate from './screens/Generate';
import EncryptionGenerate from './screens/EncryptionGenerate';
import Home from './screens/Home';
import AddUser_Screen from './screens/AddUser';
import firebase from 'firebase'
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
  apiKey: "AIzaSyD_ohJlMse2AwDvdejUaAib023jYNExw20",
  authDomain: "hash-deab0.firebaseapp.com",
  projectId: "hash-deab0",
  storageBucket: "hash-deab0.appspot.com",
  messagingSenderId: "518574452026",
  appId: "1:518574452026:web:fb4412a74f08b2bb06f403",
  measurementId: "G-6W8MYCE998"
};



const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="AUS" component={AddUser_Screen} />
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Generate" component={Generate} />
        <Stack.Screen name="EG" component={EncryptionGenerate} />
        
        
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;


/////////////////////////////////



import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, TextInput, Text } from 'react-native'
import { Ionicons } from '@expo/vector-icons';
import firebase from 'firebase'
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
export default class AddUser_Screen extends Component {

  constructor() {
  super();
    this.state = ({
      username:"",
      password:"",
      mobilenumber:"",
      cnic:"",
      city:"",
      userArr: []
    })
  }

componentDidMount(){
    const myitems = firebase.database().ref("Users");
    myitems.on("value", datasnap => {
      if(datasnap.val()){
        this.setState({userArr:Object.values(datasnap.val()) })
      }
    })
  }

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


storeitem(){
  //console.log(this.state.username, this.state.password, this.state.mobilenumber, this.state.cnic, this.state.city)
  const users = firebase.database().ref("Users");
  users.push().set({
    username:this.state.username,
    password:this.state.password,
    mobilenumber:this.state.mobilenumber,
    cnic:this.state.cnic,
    city:this.state.city
  }).then((res) =>{
  this.setState({username:"",
    password:"",
    mobilenumber:"",
    cnic:"",
    city:""})
})
}


  render(){
    return (
        <View>
        <View style={{justifyContent: 'center', alignItems: 'center', padding:10}}>
          <Text style= {{fontWeight: 'bold', fontFamily: 'Comic Sans MS'}}>Hello User!!</Text>
        </View>
          <View>
              <TextInput
                value={this.state.username}
               onChangeText={(val) => this.inputValueUpdate(val, 'username')}  
                />
              <TextInput 
               secureTextEntry 
               value={this.state.password}
               onChangeText={(val) => this.inputValueUpdate(val, 'password')}
             />
              <TextInput 
               keyboardType = "number-pad"
               value={this.state.mobilenumber}
               onChangeText={(val) => this.inputValueUpdate(val, 'mobilenumber')}
              />
              <TextInput 
              keyboardType = "number-pad"
               value={this.state.cnic}
               onChangeText={(val) => this.inputValueUpdate(val, 'cnic')}
              />
              <TextInput 
               value={this.state.city}
               onChangeText={(val) => this.inputValueUpdate(val, 'city')}
              />

            <TouchableOpacity style={styles.button} onPress = {() => this.storeitem()}>
                <Text style={{ color: "#FFF", fontWeight: "500"}}>Add User</Text>
            </TouchableOpacity>
            <TouchableOpacity style={{alignSelf: "center", marginTop: 32}} 
            onPress={() => this.props.navigation.navigate("SearchUser")}>
                <Text style={{ color: "#414959", fontSize: 16}}>
                    Search a User? <Text style={{ fontWeight: "500", color: "#E9446A"}}>User Details</Text>
                </Text>
            </TouchableOpacity>
          </View>
          </View>
                
    );
  }
}
const styles = StyleSheet.create({
  
    button: {
        marginTop: 32,
        marginHorizontal: 30,
        backgroundColor: "#E9446A",
        borderRadius: 4,
        height: 52,
        alignItems: "center",
        justifyContent: "center"
    }
    })


Solution 1:[1]

Well this piece of code worked for me. You may get the result if you try this out.

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/database";

const firebaseConfig = {
    apiKey: process.env.REACT_APP_FIREBASE_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
    appId: process.env.REACT_APP_FIREBASE_APP_ID,
  };
  firebase.initializeApp(firebaseConfig);

  export const firebaseAuth = firebase.auth();

  export const firestore = firebase.firestore();

  export const realtime = firebase.database();

  export default firebase;

Here process.env.REACT_APP_FIREBASE_KEY, refers to the apiKey provided by firebase which differs for each project. I've kept it in a .env file for security reasons.

Later, you can import it in other components like this: import {firestore} from './Firebase'; For Example, to use firestore:

import React, { useState } from 'react';
import {firestore} from './Firebase';
import {serverTimestamp} from "firebase/firestore";

//when you're submitting data to firestore

const formSubmit =(e) =>{
        e.preventDefault();
        firestore.collection("customers").doc(`GGTD${data.phone}`).set({
            name : data.name,
            address: data.address,
            phone : data.phone,
            date : serverTimestamp(),
        })      
        .then(() =>{
            alert(`Data recorded.`)
            setData({
                name:"",
                phone:"",
                address:"",
            })
        }).catch(error => {
            alert(error.message);
        });
    };

My firebase version is 9.1.1. In older versions you need not have to add compat during import. But in this version it is expected. You can also see that I've used serverTimestamp function directly from firebase. Maybe You can try the same for other functions also, however, I've not tried into that extent. I would also recommend you to reinstall firebase package to update it into latest version.Refer to firebase Docs regarding realtime Database for more info regarding CRUD operations in realtime database. This answer is specifically for React.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1