I am getting module block error when ever I try to import firebase module
My code is as followed :
import { initializeApp } from "/firebase/app";
import { getAnalytics } from "/firebase/analytics";
import { getDatabase } from "/firebase/database";
const firebaseConfig = {
apiKey:"",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const database = getDatabase(app);
My file architecture is :
-main|---.firebase
|---firebase
|---public
|---.firebaserc
|---.gitignore
|---firebase.json
|---package-lock.json
|---package.json
CodePudding user response:
By using this line:
import { initializeApp } from "/firebase/app";
You are requesting the browser to fetch the Firebase App library module from the URL https://yourproject.web.app/firebase/app
. Because the .js
extension is missing, the hosting server is trying to send back the page https://yourproject.web.app/firebase/app.html
with a MIME type of text/html
(instead of app.js
with a MIME type of text/javascript
). Additionally, because this app.html
probably doesn't exist, it is also sending back a 404.html
page.
The modern Firebase libraries are intended to be put through a module bundler like Webpack or Rollup before being served to a browser as covered in the Firebase Getting Started documentation.
But that document also highlights the following point:
Do you use ESM and want to use browser modules? Replace all your import lines to use the following pattern:
import { } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-SERVICE.js'
(where SERVICE is an SDK name such asfirebase-firestore
).Using browser modules is a quick way to get started, but we recommend using a module bundler for production.
So to correct your imports, you need to use:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.10.0/firebase-analytics.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.10.0/firebase-database.js";
Note: To save future headaches, I recommend learning and setting up your module bundler now.