按官方教程引入Firebase CDN提示auth等模块无对应导出报错
问题原因
这个报错是导入命名不符合Firebase 9.x模块化API规范导致的,不是官方教程错误,你只截取了教程中导入部分的代码,遗漏了API命名规则和后续初始化逻辑。
Firebase 9.x 开始全面采用支持Tree Shaking的模块化设计,各服务模块不会直接导出auth、firestore这类实例对象,而是导出对应服务的初始化方法、功能函数。
修复步骤
- 修正导入的命名
你之前的导入写法是Firebase 8.x及更早版本的兼容版写法,模块化版本的正确导入及使用逻辑如下:
<body> <!-- Insert this script at the bottom of the HTML, but before you use any Firebase services --> <script type="module"> import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-app.js' // 修正导入的方法名 import { getAnalytics } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-analytics.js' import { getAuth } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-auth.js' import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.4.1/firebase-firestore.js' // 第二步:填写你的Firebase项目配置 const firebaseConfig = { // 替换成你自己项目的配置参数 apiKey: "xxx", authDomain: "xxx", projectId: "xxx", storageBucket: "xxx", messagingSenderId: "xxx", appId: "xxx", measurementId: "xxx" }; // 第三步:先初始化Firebase实例,再获取对应服务 const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const auth = getAuth(app); const db = getFirestore(app); // 后续就可以正常使用auth、db等服务实例 </script> </body>
- 补充配置和初始化逻辑
你原来的代码只完成了导入步骤,既没有传入自己的项目配置调用initializeApp,也没有调用服务初始化方法获取实例,是无法正常使用Firebase服务的。
内容的提问来源于stack exchange,提问作者lowkey
相关产品推荐
相关产品推荐

