Search code examples
javascriptgoogle-cloud-firestorefirebase-authentication

Firebase 9 modular -how to start


I try to start playing with Firebase 9. I use VSCode and export using npm (in vscode)

   <script src="https://www.gstatic.com/firebasejs/9.0.0-beta.5/firebase-app-compat.js"></script>
   
    <script src="https://www.gstatic.com/firebasejs/9.0.0-beta.5/firebase-analytics-compat.js"></script>
  
    <script src="https://www.gstatic.com/firebasejs/9.0.0-beta.5/firebase-auth-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.0-beta.5/firebase-firestore-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.0-beta.5/firebase-storage-compat.js"></script>
    <!-- init -->
    <script defer src="firebase/init.js" type="text/javascript"></script>

    
    <script type="module">
    import {
        getAuth,
        onAuthStateChanged
    } from "firebase/auth";

    const auth = getAuth(firebaseApp);
    onAuthStateChanged(auth, user => {
        console.log(user)
    });
      </script>

Error

Uncaught TypeError: Failed to resolve module specifier "firebase/auth". Relative references must start with either "/", "./", or "../".


Solution

  • I ran into the same issue and was able to resolve it by closely watching David's video around the 5:40 timestamp.

    Here is the basic boilerplate that works when serving locally:

    import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
    import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
    
    const firebaseApp = initializeApp({
      // (insert your Firebase configuration here)
      });
    
      const auth = getAuth(firebaseApp);
    
      onAuthStateChanged(auth, user => {
        if (user) {
          console.log('Logged in as ${user.email}' );
        } else {
          console.log('No user');
        }
      });
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Getting started with Firebase Auth</title>
        <script type="module" src="/index.js"></script>
    </head>
    <body>
        
    </body>
    </html>