Skip to content
Advertisement

How can I fix “Failed to compile src/index.js ‘firebase’ is not defined no-undef”?

I am trying to use a React web app to read and write stuff in a Firebase realtime database. Every time I run “npm run start”, I get this error message.

Failed to compile
src/index.js
  Line 25:1:   'firebase' is not defined  no-undef
  Line 28:16:  'firebase' is not defined  no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.

This is what package.json, src/index.js, build/index.html, and public/index.html looked like when I first got this error. (is it bad to have 2 index.html files?)

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.12.2",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "firebase": "^9.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-config": "^5.1.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

import React from 'react';
import ReactDOM from 'react-dom';
//import './index.css';
//import App from './App';
//import reportWebVitals from './reportWebVitals';
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const config = {
  apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
  authDomain: "test-c2ec9.firebaseapp.com",
  projectId: "test-c2ec9",
  storageBucket: "test-c2ec9.appspot.com",
  messagingSenderId: "11138018851",
  appId: "1:11138018851:web:ecfb63337ca11f62028b96",
  measurementId: "G-3S1M3601YR"
};

// Initialize Firebase
firebase.initializeApp(config);

// Get a reference to the database service
var database = firebase.database();
const app = initializeApp(config);
const analytics = getAnalytics(app);

ReactDOM.render(
  <React.StrictMode>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. 
//reportWebVitals();

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Welcome to Firebase Hosting</title>

    <!-- update the version number as needed -->
    <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
    <!-- include only the Firebase features as you need -->
    <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
    <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
    <!-- 
      initialize the SDK after all desired features are loaded, set useEmulator to false
      to avoid connecting the SDK to running emulators.
    -->
    <script defer src="/__/firebase/init.js?useEmulator=true"></script>

    <style media="screen">
      body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
      #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
      #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
      #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
      #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
      #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
      #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
      #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
      @media (max-width: 600px) {
        body, #message { margin-top: 0; background: white; box-shadow: none; }
        body { border-top: 16px solid #ffa100; }
      }
    </style>
  </head>
  <body>
    <div id="message">
      <h2>Welcome</h2>
      <h1>Firebase Hosting Setup Complete</h1>
      <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
      <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
    </div>
    <p id="load">Firebase SDK Loading&hellip;</p>

    <script>
      document.addEventListener('DOMContentLoaded', function() {
        const loadEl = document.querySelector('#load');
        // // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
        // // The Firebase SDK is initialized and available here!
        //
        // firebase.auth().onAuthStateChanged(user => { });
        // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
        // firebase.firestore().doc('/foo/bar').get().then(() => { });
        // firebase.functions().httpsCallable('yourFunction')().then(() => { });
        // firebase.messaging().requestPermission().then(() => { });
        // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
        // firebase.analytics(); // call to activate
        // firebase.analytics().logEvent('tutorial_completed');
        // firebase.performance(); // call to activate
        //
        // // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥

        try {
          let app = firebase.app();
          let features = [
            'auth', 
            'database', 
            'firestore',
            'functions',
            'messaging', 
            'storage', 
            'analytics', 
            'remoteConfig',
            'performance',
          ].filter(feature => typeof app[feature] === 'function');
          loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
        } catch (e) {
          console.error(e);
          loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
        }
      });
    </script>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="/__/firebase/8.10.0/firebase-app.js"></script>

    <!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
    <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
    <!-- Initialize Firebase -->
    <script src="/__/firebase/init.js"></script>
  </body>
</html>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="/__/firebase/8.10.0/firebase-app.js"></script>

    <!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
    <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
    <!-- Initialize Firebase -->
    <script src="/__/firebase/init.js"></script>
  </body>
</html>

Lines 25 and 28 in src/index.js are “firebase.initializeApp(config);” and “var database = firebase.database();”, respectively. You should be able to reproduce this error by following these steps:

create test/package.json, test/src/index.js, test/build/index.html, and test/public/index.html
copy and paste the above 4 snippets into their respective files
save the 4 files
open a command line interface
use cd to navigate to the test folder
run “npm install”
run “npm run start”

Commenting out lines 25 and 28 causes a much longer error message that starts with “Firebase: No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app/no-app).” When I searched that error message, I got results telling me to add those lines back into index.js, which leads me back to this “‘firebase’ is not defined” error. Additionally, I tried each of these things, and I still got the same error message.

restarting my computer
following this tutorial
changing line 28 to “var rootref = firebase.database().ref();”
running “npm start” instead of “npm run start”
pasting this snippet in the head part of build/index.html and public/index.html

<script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>

pasting this snippet in the head part of build/index.html and public/index.html

<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>

pasting this snippet in the head part of build/index.html and public/index.html

<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />

pasting this snippet in the head part of build/index.html and public/index.html

<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>

copying this snippet from the head part of build/index.html and pasting it in public/index.html

<!-- update the version number as needed -->
<script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
<script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
<!-- 
  initialize the SDK after all desired features are loaded, set useEmulator to false
  to avoid connecting the SDK to running emulators.
-->
<script defer src="/__/firebase/init.js?useEmulator=true"></script>

Is there anything else that I can try?

Advertisement

Answer

Recently, Firebase announced that version 9 of Firebase SDK JS is generally available. This was done to do some optimisations. Try using:

import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';

and

const firebaseApp = initializeApp({ /* config */ });
const auth = getAuth();
onAuthStateChanged(auth, user => { console.log(user); });

instead of

import firebase from 'firebase/app';
import 'firebase/auth';

and

const firebaseApp = firebase.initializeApp({ /* config */ });
const auth = firebaseApp.auth();
auth.onAuthStateChanged(user => { console.log(user); });

Refer to this link for further reference: https://firebase.google.com/docs/web/modular-upgrade

Advertisement