Firebase getAuth未定义错误求助:已导入但无法调用
解决Firebase模块脚本与普通脚本的作用域冲突问题
模块脚本(type="module")拥有独立作用域,你在头部模块中导入的getAuth、createUserWithEmailAndPassword等方法仅在模块内部可用,普通脚本无法直接访问这些变量,因此触发ReferenceError。此外原代码中jQuery选择器缺少#,会导致无法获取输入框的值,也需要同步修正。
方案一:统一使用ES模块脚本(推荐)
将业务逻辑脚本转为模块类型,合并Firebase初始化与业务代码,彻底避免作用域隔离问题:
<html> <head> <!--jquery, bootstrap css, firebase--> <!--jquery--> <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"> </script> <!--bootstrap--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script> </head> <body> <!--login form--> <div class="container" id="login-form"> <div class="well"> <form> <div class="mb-3"> <label for="inputEmail" class="form-label">Email address</label> <input type="email" class="form-control" id="inputEmail" placeholder="name@example.com"> </div> <div class="mb-3"> <label for="inputPassword" class="form-label">Password</label> <input type="password" class="form-control" id="inputPassword" placeholder="password"> </div> <div class="d-grid gap-2"> <button type="button" id="sign-in-button" class="btn btn-primary">Sign in</button> </div> <div class="d-grid gap-2"> <button type="button" id="create-newuser-button" class="btn btn-warning">Create new account</button> </div> <div class="d-grid gap-2"> <button type="button" id="google-login-button" class="btn btn-primary">Sign in with Google</button> </div> </form> </div> </div> <!--add hero form--> <div class="container" id="hero-form"> <div class="well"> <form> <div class="mb-3"> <label for="inputHeroname" class="form-label">Hero name</label> <input type="text" class="form-control" id="inputHeroName" placeholder="hero name"> </div> <div class="d-grid gap-2"> <button type="button" id="create-newhero-button" class="btn btn-primary">Create new hero</button> </div> </form> </div> </div> <!--scripts--> <script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js"; import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'; const firebaseConfig = { apiKey: "xx", authDomain: "xx-22.firebaseapp.com", projectId: "xx-22", storageBucket: "xx-22.appspot.com", messagingSenderId: "222", appId: "1:22:web:ccxxx", measurementId: "G-cccc" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const auth = getAuth(app); // 提前初始化auth实例 $("#create-newuser-button").click(function() { var email = $("#inputEmail").val() var password = $("#inputPassword").val() console.log("new user = " + email + " password - " + password) SignIn(email, password) }); function SignIn(email, password) { createUserWithEmailAndPassword(auth, email, password) .then((userCredential) => { const user = userCredential.user; console.log("用户创建成功:", user); }) .catch((error) => { console.log(error) }); } </script> </body> </html>
额外修正细节:
- 重复的
id="login-form"改为id="hero-form" - 按钮文字拼写错误
"reate new hero"改为"Create new hero" - 提前初始化
auth实例,无需每次调用getAuth()
方案二:将Firebase方法挂载到全局对象
如果不想改造为模块脚本,可在头部模块中将需要的方法挂载到window全局对象,让普通脚本可以访问:
修改头部的模块脚本:
<script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js"; import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'; const firebaseConfig = { apiKey: "xx", authDomain: "xx-22.firebaseapp.com", projectId: "xx-22", storageBucket: "xx-22.appspot.com", messagingSenderId: "222", appId: "1:22:web:ccxxx", measurementId: "G-cccc" }; const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); // 将Firebase方法和实例挂载到全局 window.auth = getAuth(app); window.createUserWithEmailAndPassword = createUserWithEmailAndPassword; </script>
修改body中的普通脚本:
<script> $("#create-newuser-button").click(function() { var email = $("#inputEmail").val() var password = $("#inputPassword").val() console.log("new user = " + email + " password - " + password) SignIn(email, password) }); function SignIn(email, password) { createUserWithEmailAndPassword(window.auth, email, password) .then((userCredential) => { const user = userCredential.user; }) .catch((error) => { console.log(error) }); } </script>
内容的提问来源于stack exchange,提问作者BRDroid
相关产品推荐
相关产品推荐

