[英]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.