HTML接入Firebase Auth报错initializeApp is not defined求助
问题原因
- 脚本加载顺序错误:你把
auth.js放在了Firebase SDK的前面加载,运行auth.js的时候Firebase相关方法还没被加载,自然找不到initializeApp - 你用的是Firebase 9+的模块化版本SDK,所有API都需要显式导入才能使用,不能直接全局调用
auth.js没有声明为module类型,无法导入模块化SDK导出的方法
修复步骤
1. 修改HTML脚本部分
调整脚本加载顺序,同时给auth.js加上module类型声明,修改后的脚本片段如下:
<!-- 先加载Firebase SDK --> <script src="https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js" type="module"></script> <script src="https://www.gstatic.com/firebasejs/9.1.0/firebase-auth.js" type="module"></script> <script src="https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js" type="module"></script> <!-- 再加载auth.js,且声明为module类型 --> <script type="module" src='script/auth.js' ></script>
2. 重写auth.js代码
先导入需要的Firebase方法,同时把页面onclick要调用的方法挂载到window对象上(模块化JS作用域独立,直接定义的方法页面无法访问):
// 导入需要的Firebase方法 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-analytics.js"; import { getAuth, signInWithEmailAndPassword, signOut, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-auth.js"; const firebaseConfig = { apiKey: "AIzaSyDA7bSowKL6wCYQvYshe_OeR_uOSyhUbX0", authDomain: "papamove-delivery-cb80e.firebaseapp.com", projectId: "papamove-delivery-cb80e", storageBucket: "papamove-delivery-cb80e.appspot.com", messagingSenderId: "27728242106", appId: "1:27728242106:web:745e349a85d6cafd1b6983", measurementId: "G-3H1QJ9HJTB" }; // 初始化Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const auth = getAuth(app); // 登录方法挂载到window window.signIn = async function() { const email = document.getElementById("email_field").value; const password = document.getElementById("password_field").value; try { await signInWithEmailAndPassword(auth, email, password); // 登录成功切换面板 document.getElementById("login_div").style.display = "none"; document.getElementById("user_div").style.display = "block"; } catch (error) { alert("登录失败:" + error.message); } } // 登出方法挂载到window window.signOut = async function() { try { await signOut(auth); // 登出成功切换面板 document.getElementById("login_div").style.display = "block"; document.getElementById("user_div").style.display = "none"; } catch (error) { alert("登出失败:" + error.message); } } // 页面加载自动检查登录状态 onAuthStateChanged(auth, (user) => { if (user) { document.getElementById("login_div").style.display = "none"; document.getElementById("user_div").style.display = "block"; } else { document.getElementById("login_div").style.display = "block"; document.getElementById("user_div").style.display = "none"; } });
注意事项
所有导入的Firebase SDK版本要保持一致,不要出现不同路径版本号不一致的情况。
内容的提问来源于stack exchange,提问作者Affechon
相关产品推荐
相关产品推荐

