Maheer Ali
Maheer Ali

Reputation: 36584

How to use firebase in front end as a module?

I am making a project in which I am using typescript and also using the module system(type="module"). I put the following inside my main.html file.

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

I have another file firebase.ts which contains

// @ts-nocheck;

var firebaseConfig = {
    apiKey: "AIzaSyAePVmVNzKbvbLnAGP1VVQwyEaE7pJ3a_M",
    authDomain: "chess-3ea12.firebaseapp.com",
    databaseURL: "https://chess-3ea12.firebaseio.com",
    projectId: "chess-3ea12",
    storageBucket: "chess-3ea12.appspot.com",
    messagingSenderId: "454944098464",
    appId: "1:454944098464:web:9d10fe0a1808233f5ca1c5"
  };
  // Initialize Firebase
firebase.initializeApp(firebaseConfig);

export default {
    fs: firebase.database(),
    db: firebase.database().ref(),
    auth: firebase.auth()
}

Typescript will obviously show error

Cannot find name 'firebase'

How I can fix this means that I could get firebase a module so I could import it inside any file.

Upvotes: 1

Views: 622

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370949

You can install Firebase as a dependency so that it appears in node_modules. You won't actually be using anything in it except for its definition file, though. With typeof import(...) syntax, you can import the type of a module, so import it and declare the Firebase type onto the window:

declare global {
    interface Window {
        firebase: typeof import('firebase');
    }
}

Then, you'll be able to reference window.firebase and use its types:

const { firebase } = window;
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

export default {
    fs: firebase.database(),
    db: firebase.database().ref(),
    auth: firebase.auth()
}

Upvotes: 1

Related Questions