【问题标题】:i cannot connect firebase to my html file我无法将 firebase 连接到我的 html 文件
【发布时间】:2022-03-16 21:47:49
【问题描述】:

我正在学习 net ninjas JS 课程,其中有一章是关于使用 firebase 的数据库的。但他的 firebase 代码与现在完全不同,我在 npm 和 node.js 上苦苦挣扎。我按照this 的文档进行操作,我收到“未捕获的语法错误:无法在模块外使用导入语句”。 但是当我将 type="module" 添加到 app.js 时,我得到一个不同的错误“Uncaught TypeError: Failed to resolve module specifier "firebase/app"。相对引用必须以 "/"、"./" 或 " ../"." 以下是我的代码:-

HTML :-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script src="app.js"></script>
</body>
</html>

JS:-

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore';
// 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 firebaseConfig = {
  apiKey: "AIzaS.....bFkMOXoRY",
  authDomain: "modern.....irebaseapp.com",
  projectId: "mode....nja",
  storageBucket: "modern-j......ja.appspot.com",
  messagingSenderId: "9635.....932978",
  appId: "1:96350793.......cbf567939ae91512b",
  measurementId: "G-HFN5111EHZ"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

所有内容都是从我创建的应用程序中复制粘贴的。请帮忙

【问题讨论】:

标签: javascript firebase npm


【解决方案1】:

你能把你的导入改成这样吗:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getFirestore, collection, getDocs  } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js";

你可以找到更多关于它的信息here

您正在使用浏览器模块,因此您需要使用这些导入。这就是文档中关于它的内容:

【讨论】:

  • 我刚刚添加了这个并且它有效。请问楼主的链接是从哪里得到的? (例如,如果我想进行身份验证,链接将是什么等),您能否解释为什么仅键入“firebase/firestore”会导致“未捕获的类型错误:无法解析模块说明符“firebase/app”。相对引用必须以两者任一 ”../”。”即使 type = module 被写入包含这些导入内容的文件中?
  • 我已经扩展了答案。我希望这会有所帮助。如果您需要更多信息,请告诉我。
猜你喜欢
  • 2021-09-13
  • 1970-01-01
  • 2021-03-22
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 2017-11-13
相关资源
最近更新 更多