Search code examples
typescriptfirebasefirebase-realtime-databasegoogle-cloud-firestorecreate-react-app

Cannot find module 'firebase' or its corresponding type declarations. React + TypeScript + Firebase


I wanted to change my React project that i worked on in january to use typescript. I installed all types and packages the only file that is giving me problems is the firebase file.

This is wat i was having back then Using js.

import firebase from "firebase";
import "firebase/storage";
import "firebase/auth";
import "firebase/firestore";
import dotenv from "dotenv";

dotenv.config();

const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
  measurementId: process.env.MEASUREMENT_ID,
};
const app =
  firebase.apps.length > 0
    ? firebase.app()
    : firebase.initializeApp(firebaseConfig);

const auth = app.auth();
const db = app.firestore();
const storage = app.storage();
const timestamp = firebase.firestore.FieldValue.serverTimestamp();

const EmailProvider = new firebase.auth.EmailAuthProvider();
const _ = {
  auth,
  db,
  storage,
  timestamp,
  EmailProvider,
};
export default _;

When i change to typescript I'm getting this error as i hover on the line import firebase from "firebase"; in vscode.

Cannot find module 'firebase' or its corresponding type declarations. 

This is my package.json and im using yarn:

{
  ...
  "private": true,
  "dependencies": {
    ..
    "firebase": "^9.0.0",
    ...
  },
  "scripts": {
 ..
  },
  "eslintConfig": {
   ..
  },
  "browserslist": {
 ..
  },
  "devDependencies": {
    "@types/firebase": "^3.2.1",
    "@types/react-router-dom": "^5.1.8"
  }
}

Solution

  • "firebase": "^9.0.0",
    // ...
    "@types/firebase": "^3.2.1",
    

    You may notice that these are very different version numbers. That's because firebase comes with types built in, and so the @types/firebase package is no longer needed and hasn't been updated in 4 years. Delete "@types/firebase": "^3.2.1", from your package.json and re-run yarn