簡體   English   中英

如何使用 firebase 和文檔或 window 的導入從 html 文件中獲取信息

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

當我在 package json 文件中使用導入啟用類型:模塊時,我可以毫無問題地使用導入,例如 import { ref, set,child,getDatabase,onValue,get,push, update} from "firebase/database"; 並訪問數據,但我想通過輸入或文本區域與該信息進行交互,但我無法訪問它拋出的那些 document is not defined.!

我已經閱讀了很多頁,但由於我是新手,所以我無法理解。 我無法將答案應用到我的項目中。

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

盡管如果我取出這些導入並擦除 package json 文件中的類型:模塊,我可以使用 document.getById 但我不能使用導入請幫助我! 我是新的

type: module package.json Nodejs 環境,因此出現錯誤。 后端沒有document甚至window object。

你正在做的是前端,所以使用vite / webpack (最好vite )設置一個前端環境,對你有好處。

vite真的很容易設置你正在做的事情。 Vite 入門指南

您只需將index.html放在工作文件夾的根目錄下並運行它的命令。 它加載非常快。

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-晃動)並減小 SDK 大小。

聽起來您最好使用 CDN(內容交付網絡)。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM