Typescript can't find installed package firebase

Viewed 161

I have a simple typescript project with a bunch of .ts files that I wan't compile to .js files to use in other projects.

In one file I need the package firebase but it doesn't seem to find the package. It is installed and inside the node_modules folder. When I do:

import firebase from 'firebase'; and run tsc I get

lib/api.ts:2:22 - error TS2307: Cannot find module 'firebase'.

2 import firebase from 'firebase';
                       ~~~~~~~~~~


Found 1 error.

I tried deleting node_modules folder and package-lock.json and npm uninstall firebase but nothing seems to work.

My package.json:

{
  "name": "project-models",
  "version": "1.0.1",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "private": true,
  "scripts": {
    "build": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jonas Wallmann",
  "license": "ISC",
  "dependencies": {
    "firebase": "^6.2.3"
  },
  "devDependencies": {
    "typescript": "^3.5.2"
  }
}

My tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "strict": false,                           /* Enable all strict type-checking options. */
    "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  }
}

Any ideas?

2 Answers

Perhaps the type definition files are not embedded in the primary npm package. Try running npm install @types/firebase --save-dev from the project root and try compiling again.

I was able to fix the same error by changing import 'firebase' to import 'firebase/app'. See more context here.

It fixed the import error but haven't solved the problem completely - typescript now complained that firebase.auth() is wrong because firebase doesn't have auth method. I found the solution [here]:

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
Related