Home > Net >  How to use initialized Firebase in another file?
How to use initialized Firebase in another file?

Time:07-11

I want to separate the logic in the application and created a file for Firebase initialization and a separate file for the application logic. In the application logic file, I use firebase add to database and use set(). But there is an error in the console: set is not defined at HTMLButtonElement. How can I use firebase functions in a separate file from initialization?

//firebase.js

import {
  initializeApp
} from "https://www.gstatic.com/firebasejs/9.9.0/firebase-app.js";
import {
  getDatabase,
  ref,
  set,
  onValue,
  update,
  remove,
} from "https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js";

const firebaseConfig = {
  ...
};

const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

//script.js

set(ref(database, ".../"), {
  ...
})

CodePudding user response:

You will have to use import/exports to achieve what you want.

Perhaps export whatever you wish from firebase.js:

// firebase.js
export const database = getDatabase(app);

... and import whatever you need in other files:

// script.js
import { database } from './firebase';
import { ref, set } from 'https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js';

There is also the option of exporting everything from firebase.js and you will need only 1 import, but I haven't tested it yet with remote resources:

// firebase.js, option 2
export const database = getDatabase(app);
export { set, ref } from 'https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js';
// script.js, option 2
import { database, set, ref } from './firebase';

Hope this helps and happy coding.

  • Related