如何使用 firebase 和文档或窗口的导入来从 html 文件获取信息

org*_*ses 5 javascript browser node.js firebase firebase-realtime-database

当我在包 json 文件中使用启用 type:module 的导入时,我可以毫无问题地使用导入,例如 import { ref, set,child ,getDatabase,onValue,get,push, update} from "firebase/database"; 并访问数据,但我想通过输入或文本区域与该信息进行交互,但我无法访问它抛出的信息文档未定义。!

我已经读了很多页,但由于我是新手,我无法理解。我无法将答案应用到我的项目中。

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
Run Code Online (Sandbox Code Playgroud)

虽然如果我取出这些导入并删除包 json 文件中的 type:module ,我可以使用 document.getById 但我不能使用导入,请帮助我!我是新的

Ale*_*ill 0

Firebase Web SDK 理想情况下需要模块捆绑器 (Webpack/Rollup) 或 JavaScript 框架工具,如 Vue、React、Angular 等,因为 Web SDK(或至少版本 9)经过优化,可与模块捆绑器配合使用,以消除未使用的代码(树状代码)。晃动)并减小 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
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)