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

React项目使用Firebase Firestore Timestamp遇'firebase未定义'错误求助

解决Firebase Timestamp "firebase is not defined" 错误

你当前使用的是Firebase v9+ 模块化API,而非旧版的命名空间模式,同时你的firebase.js初始化文件也没有导出全局firebase对象,因此直接调用firebase.firestore.Timestamp会触发未定义错误。以下是两种可行的解决方式:

方案一:从自定义初始化文件导入Timestamp

  1. 修改firebase.js,在Firestore导入中加入Timestamp并导出:
import { initializeApp } from "firebase/app";
import { getFirestore, Timestamp } from "firebase/firestore"; // 新增Timestamp导入
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  // 你的配置内容
};

export const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth(app);
export const storage = getStorage(app);
export { Timestamp }; // 导出Timestamp
  1. 在需要使用的组件中导入并使用:
import { Timestamp } from './firebase'; // 路径根据你的文件位置调整
import moment from 'moment';

// 生成Timestamp
const duedate = moment().add(1, 'd').toDate();
const timestamp = Timestamp.fromDate(duedate);

方案二:直接从Firebase Firestore包导入Timestamp

无需修改firebase.js,直接在组件中导入Timestamp:

import { Timestamp } from 'firebase/firestore';
import moment from 'moment';

// 生成Timestamp
const duedate = moment().add(1, 'd').toDate();
const timestamp = Timestamp.fromDate(duedate);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:45:08