使用Firebase Firestore配置网站数据库时遇模块及变量未定义问题
解决Firebase Firestore配置中的两个错误
1. 解决"Cannot use import statement outside a module"错误
这个错误是因为浏览器默认将脚本视为非ES模块,只需在HTML的<script>标签中添加type="module"属性即可:
<script type="module" src="index.js"></script>
2. 解决"Uncaught ReferenceError: ms is not defined"错误
你提供的代码里并未使用ms变量,这个错误通常由以下原因导致,按顺序排查:
原因1:ES模块导入路径错误(最可能)
如果没有使用Webpack、Vite这类打包工具,直接在浏览器中运行ES模块,不能用npm风格的导入路径("firebase/app"),必须使用Firebase CDN的完整模块URL。修改index.js中的导入语句:
// 替换原有的import语句 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"; import { getFirestore, collection, getDocs, addDoc, deleteDoc, doc } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-firestore.js";
注意:可以替换为你需要的Firebase版本号,确保两个模块版本一致
原因2:其他脚本冲突
检查HTML页面中是否有其他未添加type="module"的脚本,这类脚本可能在全局作用域中引用了未定义的ms变量。可以暂时移除其他脚本,验证是否是冲突导致。
原因3:浏览器缓存
强制刷新页面(Ctrl+F5)或清除浏览器缓存,避免加载旧的、有问题的脚本文件。
验证修改后的完整代码
修改导入路径后,你的index.js代码如下:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"; import { getFirestore, collection, getDocs, addDoc, deleteDoc, doc } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-firestore.js"; const firebaseConfig = { apiKey: "AIzaSyAeQ_9V11B9Jxo8riUZq6nuUtZW76Mizvc", authDomain: "fb-auth-86194.firebaseapp.com", projectId: "fb-auth-86194", storageBucket: "fb-auth-86194.appspot.com", messagingSenderId: "100065049962", appId: "1:100065049962:web:2fc4220892c9197ec5b913", measurementId: "G-76BRMWM1XM", }; // init firebase app const app = initializeApp(firebaseConfig); // init services const db = getFirestore(app); // collection ref const colRef = collection(db, 'books') // get collection data getDocs(colRef) .then((snapshot) => { let books = [] snapshot.docs.forEach((doc) => { books.push({ ...doc.data(), id: doc.id }) }) console.log(books) }) .catch(err => { console.log(err.message) }) // adding data const addBookForm = document.querySelector('.add') addBookForm.addEventListener('submit', (e) => { e.preventDefault() addDoc(colRef, { title: addBookForm.title.value, author: addBookForm.author.value, }) .then(() => { addBookForm.reset() }) }) // deleting data const deleteBookForm = document.querySelector('.delete') deleteBookForm.addEventListener('submit', (e) => { e.preventDefault() const docRef = doc(db, 'books', deleteBookForm.id.value) deleteDoc(docRef) .then(() => { deleteBookForm.reset() }) })
内容的提问来源于stack exchange,提问作者AD_
相关产品推荐
相关产品推荐

