如何解决Firebase项目中const auth提示未定义的报错问题
问题原因
type="module" 类型的脚本属于ES模块,内部声明的变量默认仅在模块作用域内生效,不会暴露到全局window对象。你后续引入的auth.js是普通脚本,运行在全局作用域,因此无法访问模块内定义的auth常量。
此外你还存在一个API调用方式的问题:你使用的是Firebase 9+的模块化版本,已经不再支持auth.createUserWithEmailAndPassword这种链式调用写法,所有操作方法都是独立导入的函数。
解决方案
方案1:最小改动方案(污染全局作用域)
仅需两处修改即可快速解决问题:
- 在HTML的内联module脚本中,初始化
auth后将其挂载到全局window:
const auth = getAuth(app); const db = getFirestore(app); // 新增以下代码 window.auth = auth; window.db = db; // 如果需要用到db也可以挂载
- 修改auth.js中的注册调用逻辑,适配Firebase 9+的API规范:
// 首先在auth.js开头导入createUserWithEmailAndPassword方法 import { createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js"; // 原有注册逻辑改成如下写法 createUserWithEmailAndPassword(auth, email, pass).then(cred => { console.log(cred); });
方案2:标准模块化方案(无全局污染)
按ES模块规范重构代码,更符合现代前端开发规范:
- 新建
js/firebase-init.js文件,将Firebase初始化逻辑抽离为独立模块并对外导出实例:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js"; import { getAuth } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js"; import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js"; const firebaseConfig = { apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric", authDomain: "auth-project-38aaa.firebaseapp.com", projectId: "auth-project-38aaa", storageBucket: "auth-project-38aaa.appspot.com", messagingSenderId: "431888894254", appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf", measurementId: "G-6BBPCJ3814" }; const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); export const auth = getAuth(app); export const db = getFirestore(app);
- 修改HTML中的脚本引入配置:
- 删除原来内联的Firebase初始化module脚本
- 将auth.js的引入改为module类型:
<script src="vendor/jquery/jquery.min.js"></script> <script type="module" src="js/auth.js"></script>
- 修改auth.js代码,导入所需依赖并适配API规范:
import { auth } from './firebase-init.js'; import { createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js"; const signUpForm = document.querySelector('#register-form'); signUpForm.addEventListener('submit', (e) => { e.preventDefault(); // get user info const name = signUpForm['name'].value; const email = signUpForm['email'].value; const pass = signUpForm['pass'].value; const rePass = signUpForm['re_pass'].value; const agreeTerm = signUpForm['agree-term'].value; console.log(name, email, pass, rePass, agreeTerm); // sign up the user createUserWithEmailAndPassword(auth, email, pass).then(cred => { console.log(cred); }); });
内容的提问来源于stack exchange,提问作者Donn Deparsio
相关产品推荐
相关产品推荐

