You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase引入Firestore报错‘Service firestore is not available’求助

解决Firebase Firestore报错「Service firestore is not available」及模块导入问题

问题分析

你遇到的两个核心问题:

  1. 裸模块导入(firebase/firebase-app.js)报错:浏览器原生不支持直接解析裸模块标识符,必须使用相对路径、绝对路径或CDN链接。
  2. Service firestore is not available错误:本质是Firestore模块未被正确加载或注册到Firebase App实例中,不管是直接从node_modules导入还是错误的CDN链接都可能导致这个问题。

解决方案

方案1:使用打包工具(推荐,适配npm管理工作流)

既然你用npm管理依赖,最稳妥的方式是用打包工具(如Vite、Webpack)处理模块解析,步骤如下:

  1. 初始化一个Vite项目(以Vanilla JS为例):
    npm create vite@latest my-project -- --template vanilla
    cd my-project
    
  2. 安装Firebase依赖:
    npm install firebase@9.19.1
    
  3. 修改你的firebase.js为标准模块化导入:
    import { initializeApp } from "firebase/app";
    import { getFirestore, collection, addDoc } from "firebase/firestore";
    
    const firebaseConfig = {
      // 你的Firebase配置信息
    };
    
    export const app = initializeApp(firebaseConfig);
    export const db = getFirestore(app);
    export { collection, addDoc };
    
  4. 在需要使用的脚本中正常导入:
    import { db, collection, addDoc } from "./firebase.js";
    // 后续操作Firestore
    
  5. 开发时运行npm run dev,打包部署时执行npm run build,再将dist目录部署到Firebase托管。

方案2:不使用打包工具,改用官方模块化CDN

如果不想引入打包工具,需要使用Firebase官方提供的模块化CDN链接,确保模块完整加载:

  1. 在HTML中先导入Firebase核心及Firestore模块:
    <script type="module">
      import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.19.1/firebase-app.js';
      import { getFirestore, collection, addDoc } from 'https://www.gstatic.com/firebasejs/9.19.1/firebase-firestore.js';
    
      const firebaseConfig = {
        // 你的Firebase配置信息
      };
    
      const app = initializeApp(firebaseConfig);
      const db = getFirestore(app);
    
      // 将实例挂载到window,供其他脚本使用
      window.firebaseApp = app;
      window.db = db;
      window.collection = collection;
      window.addDoc = addDoc;
    </script>
    
  2. 在你的自定义脚本中直接使用挂载到window的实例:
    // your-script.js
    async function addData() {
      try {
        await addDoc(collection(window.db, "your-collection"), {
          // 数据内容
        });
      } catch (e) {
        console.error("添加文档失败: ", e);
      }
    }
    

关键注意事项

  • 不要直接从node_modules目录导入模块:浏览器无法正确解析这类路径,且容易导致模块加载不完整,触发服务不可用错误。
  • 确认Firebase配置中的projectId与控制台中Firestore数据库的项目ID完全一致,配置错误也可能间接引发服务加载问题。

内容的提问来源于stack exchange,提问作者davidlongjhons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:37:36