firebase not defined Vue.js - javascript

I'm new in vue.js and I'm learning vue.js from documentation and tutorial on internet, now I'm trying make app with Firebase and vue.js but my when I run it, an error says:
-firebase not defined
However, I'm pretty sure that I imported it. Here my code:
main.js:
import Vue from 'vue'
import App from './App'
import router from './router'
import * as firebase from "firebase"
var config = {
apiKey: "###########",
authDomain: "###########",
databaseURL: "###########",
projectId: "###########",
storageBucket: "###########",
messagingSenderId: "###########"
};
firebase.initializeApp(config);
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
firebase,
components: { App },
template: '<App/>'
})
This my component register:
<template>
<div class="login">
<h3>Lets Register</h3>
<input type="email" v-model="email">
<input type="password" v-model="password">
<button v-on:click="register">Submit</button>
<p><router-link to="/Login"> Login? </router-link></p>
</div>
<script>
export default {
name: 'Register',
data () {
return{
email: '',
password: ''
}
},
methods:{
register : function(){
firebase.auth().createUserWithEmailAndPassword(this.email,this.password).then(
function (user) {
alert('Account been created')
},
function(err){
alert('opps'+ err.message)
}
);
}
}
}
Any help would be appreciated.

In main.js just register firebase as global with Vue.use(firebase) like this, and all components can access that.
import firebase from 'firebase'
Vue.use(firebase)
var config = {
apiKey: "####",
authDomain: "####",
databaseURL: "####",
projectId: "####",
storageBucket: "####",
messagingSenderId: "####"
};
firebase.initializeApp(config);
new Vue({
el: '#app',
render: h => h(App),
router : router,
firebase: firebase,
})
And in your components don't forget to import that like this:
import firebase from 'firebase'

It's really undefined at your component, I have with this problem too. How to solve it? Modules.
Create a Js file called firebase.service.js, on this file you'll define every function that uses firebase, you'll configure the firebase at this file too, then you'll export the functions to the other files, where you'll import and use them, just like this:
firebase.service.js
import * as firebase from 'firebase'
var config = { // put here your credentials
apiKey: apiKey,
authDomain: authDomain,
databaseURL: databaseURL,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId
}
firebase.initializeApp(config)
var auth = firebase.auth()
var db = firebase.database()
export function signOut (callback) {
auth.signOut().then(value => {
callback()
}, err => { callback(err) })
}
Components
<script>
import { signOut } from './firebase.services'
// use it here
</script>
You can't export firebase itself, because it'll throw an error saying that the firebase was already initialized.

You should import firebase in every component you want to use it in. Looks like you are importing firebase now in a different file so just add the import to the component.

Just adding some more info in case someone finds it useful. First off, only load components of firebase that you need. Gabriel Carneiro's response is really the base of the following...
Your firebase.js where you initialize and export your methods, modules, etc
/*this will import all the firebase which can be a bottleneck */
// import * as firebase from 'firebase'
/*better only importing what you need*/
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';
const config = {
apiKey: "***************",
authDomain: "***************",
databaseURL: "***************",
projectId: "***************",
storageBucket: "***************",
messagingSenderId: "***************",
appId: "***************"
};
/*OptionalPrjName is optional that you can initialize your firebase with
it in case you are using more than one project or config file ,
it's optional as firebase can initialize without this name*/
firebase.initializeApp(config, "OptionalPrjName");
const auth = firebase.auth(firebase.app("OptionalPrjName"));
const firestore = firebase.firestore(firebase.app("OptionalPrjName"));
const functions = firebase.functions(firebase.app("OptionalPrjName"));
/*create modules ; say one for sign up , etc , another for functions, etc ... */
const app_firebase = {
signout: () => console.log(`firebase is` , firebase),
test: () => console.log(`testing`),
}
/*export them here so you can import them individually where you need in your components */
export {
app_firebase,
}
/*another way of only exporting your functions, etc. I like the above better becuase it helps bundling similar
functionalities together under a name space ; make sure you don't create confusion by assigning similar naming
so I always add something like app_ to my names in the above exports*/
export function fire_auth(callback) {
console.log(`firebase `, auth, firestore, functions);
}
your component, in which you can only import what you need to use (let call the component signup.vue) and say we have placed in the root of our directory so we access it in views like ../firebase :
<template>
<div class="signup">
<h2>signup</h2>
<button type="button" #click="signup">Sign Up</button>
<router-link to="/login">Login</router-link>
</div>
</template>
<script>
import { fire_auth, app_firebase } from '../firebase';
export default {
name: 'signup',
data() {
return {}
},
methods: {
signup: function() {
fire_auth();
app_firebase.test();
}
}
}
</script>
<style scoped>
/* scoped attr limits style to this component only */
</style>

Related

ERROR in Module not found: Error: Package path . is not exported from package

Firebase.js:
import firebase from "firebase";
const firebaseConfig = {
apiKey: <<API_KEY>>,
authDomain: "fir-42683.firebaseapp.com",
projectId: "fir-42683",
storageBucket: "fir-42683.appspot.com",
messagingSenderId: "950284829228",
appId: "1:950284829228:web:f9e6862d17650cfca38789",
measurementId: "G-VWT1P7ES8S"
};
export const db = firebase.initializeApp(firebaseConfig)
App.js
import {db } from './Firebase'
I wrote just a simple code for read data from firebase. but now, iam stuck on this error, what will i do.
ERROR in ./src/Firebase.js 3:0-32 Module not found: Error: Package path . is not exported from package D:\BROCAMP\Week 15\olx\node_modules\firebase (see exports field in D:\BROCAMP\Week 15\olx\node_modules\firebase\package.json)
The problem is const db = firebase.initializeApp(firebaseConfig)
You missed one step, this is actually const app = firebase.initializeApp(firebaseConfig)
Consider this hook which can get your db:
useGetFirestore.ts
import { getApp } from 'firebase/app';
import { getFirestore, Firestore } from 'firebase/firestore';
const useGetFirestore = (): Firestore => {
const app = getApp();
return getFirestore(app);
};
export default useGetFirestore;
The code you are calling db is actually app and that code just needs to run at the top of your app before anything:
const app = initializeApp(firebaseConfig);
Sometimes you only need this:
initializeApp(firebaseConfig);

NextAuth and Firebase causing SyntaxError Cannot use import statement outside a module

I'm new to both Next.js and Firebase. I've been trying to use NextAuth.js to authenticate with Discord for my firebase app. However, I ran into an error.
I've tried adding "type": "module" into my package.json file and converting all my imports into requires instead but I still get the same error.
This is my firebase.js
import firebase from "firebase/compat/app";
import { getApps, getApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
export const app = getApps.length > 0 ? getApp() : firebase.initializeApp(firebaseConfig);
export const firestore = getFirestore(app);
export const storage = getStorage(app);
This is my [...nextauth].js
import NextAuth from "next-auth";
import DiscordProvider from 'next-auth/providers/discord';
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { firebaseConfig } from "../../../lib/firebase";
export default NextAuth({
providers: [
DiscordProvider({
clientId: process.env.DISCORD_ID,
clientSecret: process.env.DISCORD_SECRET
}),
],
adapter: FirestoreAdapter(firebaseConfig),
})
Any help would be much appreciated
I went through this as well. I found using a simple config easier and exporting the default app into your component. Then in the component, add the extra functionality.
Here is my config;
import { initializeApp } from 'firebase/app';
// Initialize Firebase
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
}
const app = initializeApp(firebaseConfig)
export default app;
then in controller...
import { getDatabase } from 'firebase/database';
import app from '../services/firebase';
const rtdb = getDatabase(app);

Importing Firebase database object in React results in Uncaught SyntaxError: Cannot use import statement outside a module

I'm working on a project where I need to implement Firestore database in a React app, which I do like this: I have a firebase.js file in the src directory which contains information about Firebase and exports a db object,
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// Firebase project configuration
const firebaseConfig = {
apiKey: ...
authDomain: ...
databaseURL: ...
projectId: ...
storageBucket: ...
messagingSenderId: ...
appId: ...
measurementId: ...
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
const db = getFirestore(app);
export { db }
Then I try to import the db object from App.js,
import React, { Component } from 'react';
import { db } from './firebase'
class App extends Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default App;
And I get the following error in the console Uncaught SyntaxError: Cannot use import statement outside a module (at bundle.js:45109:2), as a result, the component does not render.
The line in which it seems to be a problem in bundle.js:45109:2 is this:
import { registerVersion } from '#firebase/app';

Error when initializing firebase database in Reactjs

I am fairly new to react and I am trying out firebase. I am getting this error message
Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)
and I have tried many things that didnt fix it.
This is how my config looks likes
export const config = {
apiKey: "AIzaSyCrfLCYS7VuvvUVaEkfzYVdJJLeqVuZHQE",
authDomain: "crudreac.firebaseapp.com",
databaseURL: "https://crudreac.firebaseio.com",
projectId: "crudreac",
storageBucket: "crudreac.appspot.com",
messagingSenderId: "116257347605"
};
And this is how I am TRYING to initialize the databse
import { config } from './Config/config';
import firebase from 'firebase/app';
import 'firebase/database'
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.addNote = this.addNote.bind(this);
this.app = firebase.initializeApp(config);
console.log(firebase.app.name);
this.db = this.app.database().ref().child('notes');
this.state = {
notes:[],
}
}
I am probably doing the initialization wrong, so if anyone could help me out I would apreciate it
I have already tried doing
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
But it didnt help

Firebase not initializing before it gets called in other files

Im trying to use firebase in a vue project. I have other js files such as auth.js that use firebase, but im initializing it in my main.js(which should be the entry point for webpack) but it seems like the other files are getting called first? Im using vue-cli with the webpack template.
The error I am getting is
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
Here is the first part of my main.js
// main.js
import Vue from 'vue';
import firebase from 'firebase';
// import firebaseui from 'firebaseui';
import VueFire from 'vuefire';
import App from './App';
import router from './router';
import database from './js/database';
Vue.use(VueFire);
const config = {
apiKey: '***',
authDomain: '***',
databaseURL: '***',
storageBucket: '***',
messagingSenderId: '***',
};
firebase.initializeApp(config);
database.init();
This is my first time really using firebase, any ideas what going on?
This is how i did it
import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import App from './App.vue'
import { routes } from './routes'
import * as firebase from 'firebase'
import { store } from './store/store'
Vue.use(VueResource);
Vue.use(VueRouter);
const router = new VueRouter({
routes,
});
let config = {
apiKey: "XXXX",
authDomain: "XXXXXX",
databaseURL: "xXxxxxxx",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXX"
};
Vue.prototype.$firebase = firebase.initializeApp(config);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
I did not use vue fire
But i can use firebase functionality from alll over my app by calling
this.$firebase.auth()
this.$firebase.database()
this.$firebase.storage()

Categories