Import firebase firestore from CDN JS not working - javascript

I am importing Firebase Firestore from CDN to run on a local server. I imported it as the documentation says, right here: https://firebase.google.com/docs/web/alt-setup
My code :
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
import { firestore } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-firestore.js'
The problem:
Firebase app and firebase auth are imported and work perfectly however, Firestore is not being imported. I get this error:
Uncaught SyntaxError: The requested module 'https://www.gstatic.com/firebasejs/9.6.3/firebase-firestore.js' does not provide an export named 'firestore'
This is my first web project using firebase and I dont know how to move forward. Any help or suggestion will be appreciated by this newbie. If you need anymore information let me know, Thanks.

One way to import is, first create a file called firebase.js and paste this code :
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getFirestore, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js";
//add your credentials from firebase project
const firebaseConfig = {
apiKey: "YOUR-apiKey-nCVgNHJXTs",
authDomain: "YOUR-authDomain.firebaseapp.com",
projectId: "YOUR-projectId-fb",
storageBucket: "YOUR-storageBucket-fb.appspot.com",
messagingSenderId: "YOUR-messagingSenderId",
appId: "YOUR-appId-web:11c8d54e0"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
//create your custom method
export const getWolfs = () => {
return getDocs(collection(db, "yourNameCollection"));
};
Now, you can create a new file called main.js and paste this code:
import { getWolfs } from './firebase.js';
//suppose you want to display the list of wolves in the browser console
window.addEventListener("DOMContentLoaded", async (e) => {
const querySnapshot = await getWolfs();
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
});
Finally create the html file index.html and paste this code:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>firebase</title>
</head>
<body>
<h2>wolves</h2>
<!--main app-->
<script type="module" src="./main.js"></script>
</body>
</html>
Sample project:
That is all, i hope it works for you 😉

I think the source has been deprecated. Cause the explanation written like this, from this source https://firebase.google.com/docs/web/alt-setup#from-the-cdn
For most Firebase Web apps we strongly recommend using SDK version 9 via npm.
I found two ways, in version 8 you can still use that way.
<body>
<!-- Insert this script at the bottom of the HTML, but before you use any Firebase services -->
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
</body>
But if you want use in version 9, you have to use npm.
npm install firebase#9.4.1 --save
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
You can visit: https://firebase.google.com/docs/firestore/quickstart#web-version-9
Hopefully this can help you.

Have you type this in script tag
<body>
<script type="module">
// ...
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
</script>
</body>
type=module ?

Try this, this issue similar with you
import { function } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-SERVICE.js'
//Example
import { function } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-firestore.js'

Yes, it does not provide an export named 'firestore' but
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.n.n/firebase-firestore.js";
const firestore = getFirestore();
console.log(firestore);
does.
See: getFirestore()

Related

How to use imports for firebase and document or window to get info from the html file

When I use imports enabling type:module in the package json file I can use without problems the imports such as import { ref, set,child ,getDatabase,onValue,get,push, update} from "firebase/database"; and access the data, but I want to interact with that information with inputs or text areas but I cannot access those it throws document is not defined.!
I have read many pages but as I am new I cannot get it. I cannot apply the answer to my project.
import { ref, set,child ,getDatabase,onValue,get,push, update} from "firebase/database";
import { getAuth, onAuthStateChanged } from "firebase/auth";
//to get info from firebase
var headbox = document.getElementById('a'); // from Html to manage info send and show it here
var bodybox = document.getElementById('b'); // error when I want to read this
Although if I take those imports out and erase type:module in the package json file, I can use document.getById but I cannot use imports please help me! I am new
type: module in package.json is for use in Nodejs environments, hence the error. Backend has no document or even window object.
What you are doing is frontend, so setting up a frontend environment using vite/webpack (preferably vite), would do you some justice.
vite is really easy to setup for what you are doing. Vite Getting Started Guide.
You just place your index.html at the root of your working folder and run it's commands. It loads very quickly.
The Firebase Web SDK ideally requires module bundlers (Webpack/Rollup) or JavaScript framework tooling like Vue, React, Angular, etc because the Web SDK (or at least version 9) is optimized to work with module bundlers to eliminate unused code (tree-shaking) and decrease SDK size.
Sounds like you would be better off using CDN (content delivery network).
JavaScript
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js';
import { ref, set, child, getDatabase, onValue, get, push, update } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js';
import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js';
const firebaseConfig = {
apiKey: 'xxx',
authDomain: 'xxx',
projectId: 'xxx',
storageBucket: 'xxx',
messagingSenderId: 'xxx',
appId: 'xxx',
measurementId: 'xxx'
};
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth();
window.addEventListener('DOMContentLoaded', (event) => {
const headbox = document.getElementById('a');
const bodybox = document.getElementById('b');
onAuthStateChanged(auth, (user) => {
if (user) {
// user.uid
}
});
});
HTML
<html>
<head>
...
</head>
<body>
<div id="a">Head Box</div>
<div id="b">Body Box</div>
<script type="module" src="your-javascript-file.js"></script>
</body>
</html>

Uncaught SyntaxError: Cannot use import statement outside a module (Using Firebase)

I'm having a problem storing data to my database through my html form, The error I get comes from my import statement which is: Uncaught SyntaxError: Cannot use import statement outside a module!
Code below:
import {
initializeApp
} from "firebase/app";
const firebaseConfig = {
apiKey: "MY_API_KEY", //actual values are in my code, changed here for security purposes.
authDomain: "My_auth_Domain",
databaseURL: "FirebaseDb_URL",
projectId: "Project_id",
storageBucket: "storageBucket",
messagingSenderId: "SenderId",
appId: "appId"
};
const app = initializeApp(firebaseConfig);
let inviteInfo = firebase.database().ref("inviteinfos");
document.getElementById("#regform", submitForm);
function submitForm(e) {
let name = document.getElementsByName("fullname").value;
let compName = document.getElementsByName("compName").value;
let email = document.getElementsByName("email").value;
let address = document.getElementsByName("address").value;
let contact = document.getElementsByName("contact").value;
console.log(name, compName, email, address, contact);
saveContactInfo(name, compName, email, address, contact);
document.getElementById("#regform").reset();
}
What I have tried so far:
changed import statement to the following
const {initializeApp} = require("firebase/app");
used import with firebase provided link
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
used const with the firebase provided link:
const {initializeApp} = require("https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js");
Moved js from app.js into the main html page with a script tag of type module.
used npm to install firebase to retrieve the modules.
in regards to the link based solution I tried to remove the -app to see if it made a difference but it did not.
So far none of these have worked for me, the table I am trying to store information to currently does not exist but research has shown that running even without the table existing will create the table automatically for me.
Load app.js like this:
<script type="module" src="./app.js"></script>
Inside app.js, you import firebase-app like this:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
// ...
Here's an example (I can't use a separate file for app.js, but this demonstrates that it does work):
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
// Check that it worked and returned a function:
console.log(typeof initializeApp); // "function"
</script>
You don't need a script tag for firebase-app.js at all, it'll get loaded by the browser because of your import.
Note that this will be using modules natively in the browser. All modern browsers directly support doing that, but obsolete ones like Internet Explorer don't, and separately loading modules like this can involve lots of small HTTP calls rather than a few larger ones, which can cause page load delays even with modern net protocols like SPDY. For that reason, people often use bundlers like Vite, Rollup, Webpack, etc. that combine modules into a small number of bundle files. If you like, you could look at doing that. But again, modern browsers natively support modules, so you don't have to.
Using "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js" in every place you want to import from firebase-app may be a bit of a pain. You have two options to make it easier:
1. In Chromium-based browsers (only, sadly, for now), you can use an import map:
<script type="importmap">
{
"imports": {
"firebase-app": "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js"
}
}
</script>
That tells your browser that when you import from "firebase/app", it should use "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js".
Live Example:
<script type="importmap">
{
"imports": {
"firebase/app": "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js"
}
}
</script>
<script type="module">
import { initializeApp } from "firebase/app";
// Check that it worked and returned a function:
console.log(typeof initializeApp); // "function"
</script>
2. If you can't use import maps, you can write a module that re-exports everything from firebase-app, and then import from that module in your code rather than directly from firebase-app:
Your own local firebase-app.js file:
// This re-exports all of its named exports (but not its default, if any)
export * from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
/* firebase-app.js doesn't provide a default export. If it did, this is
how you'd re-export it:
export { default } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
*/
Then app.js would use firebase-app.js:
import { initializeApp } from "./firebase-app.js";
(I can't do a live example of that with Stack Snippets, but here's that on CodeSandbox.)

Firebase authentication error in javascript

I'm encountering an error when trying to add a user to firebase authentication. The const auth is defined before the script is loaded. I've tried calling with and without the app parameter. The user is not being added and I can't seem to figure this error out. I've cut out only the code I think is relevant. Apologies if this is a stupid question, I'm just diving into HTML and JS.
Error: Uncaught ReferenceError: auth is not defined
at HTMLFormElement. (auth.js:12)
From html file:
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-auth.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
<script src="js\auth.js"></script>
From js file:
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log(cred);
});
You're using the modular SDK, which means that imported names are no longer added to a global namespace. If your include file (js.auth.js) needs access to the auth service, you will need to import getAuth into that file too and initialize it there as well.

service firestore is not available

I'm trying to connect to my firestore using plain javascript. (I wanna get up to speed and running for now)
index.js:
import app from './firebase.js'
import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-firestore.js'
const db = getFirestore(app)
However, this throws an error: Uncaught Error: Service firestore is not available
firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = {
// configs
};
// Initialize Firebase
let app
export default app = initializeApp(firebaseConfig);
Then I import the script in my index.html:
<!DOCTYPE html>
....
<script type="module" src="index.html"></script>
Note: I can read and write to the firestore using firebase web interface.
So if you want to use plain js (without bundlers like webpack), you would need to put your JS code into script tag like so:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = { ... };
const app = initializeApp(firebaseConfig);
</script>
Otherwise, if you want to use it like you intended to do so, you would need to:
install a firebase package
a module bundler (e.g. webpack) to bundle the files for you
Using npm, but got the same error message.
Restarted terminal & uninstalled and reinstall firebase, then worked...not sure which one that did it though.
You need to upgrade your firestore version 9.0.0 to 9.4.0 and it work fine
import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-firestore.js";
Change your import link import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
to import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
just update the firebase version from 9.0.0 to 9.0.1

Firestore onSnapshot - firebase.firestore is not a function - Failed to resolve module specifier "firebase"

I'm just trying to learn firebase, and I wanted to use onSnapshot so switched from "realtime database" to "firestore". After switching I copied this boilerplate code:
document.addEventListener("DOMContentLoaded", evt=> {
const app = firebase.app();
const db = firebase.firestore();
db.collection('users')
.onSnapshot((snapshot) => {
console.log(`Received doc snapshot: ${snapshot}`);
}, (error) => {
console.log(`Encountered error: ${error}`);
});
});
However I got that "firebase.firestore is not a function". I found the solution here: https://stackoverflow.com/a/50684682/4907950 which is just adding:
import * as firebase from 'firebase';
import 'firebase/firestore';
However, then I get: "Uncaught TypeError: Failed to resolve module specifier "firebase". Relative references must start with either "/", "./", or "../"."
EDIT: Also worth noting that I've added <script defer src="/__/firebase/7.14.2/firebase-firestore.js"></script> to my HTML file and the error persists.
Removing:
import * as firebase from 'firebase';
import 'firebase/firestore';
From the stackoverflow post I had found, while keeping the firestore link seemed to do the trick.
For some reason I had to use the complete URL and keep them at top of <BODY> tag like this:
<body>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-storage.js"></script>
<script src="app.js"></script>
</body>
Also I had to re-install all requires stuff using Firebase CLI. It worked perfectly thereafter.

Categories