Firebase Analytics with Nextjs -窗口未定义

oknrviil  于 2023-05-01  发布在  其他
关注(0)|答案(3)|浏览(252)

我正在尝试在Next中实现和导出firebase分析模块。js(firebase v9)
我得到错误**“ReferenceError:window is not defined”**for the following code snippet.以前的所有功能都很好。
有办法解决吗?

import { initializeApp, getApps, getApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from 'firebase/auth'
import { getFirestore } from '@firebase/firestore'

const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
const auth = getAuth();
const db = getFirestore(app)

// try to add analytics
const analytics = getAnalytics(app)
export {auth, db, analytics}
mctunoxg

mctunoxg1#

Next.js:

import {initializeApp} from 'firebase/app';
import {getFirestore} from 'firebase/firestore';
import {getAnalytics} from 'firebase/analytics';

const firebaseConfig = JSON.parse(
    process?.env?.FIREBASE_CONFIG ?? '{}',
);

let analytics; let firestore;
if (firebaseConfig?.projectId) {
  // Initialize Firebase
  const app = initializeApp(firebaseConfig);

  if (app.name && typeof window !== 'undefined') {
    analytics = getAnalytics(app);
  }

  // Access Firebase services using shorthand notation
  firestore = getFirestore();
}

export {analytics, firestore};
62o28rlo

62o28rlo2#

版本9 SDK不检查窗口对象。您必须使用类似typeof window !== "undefined"的东西来实现自己的检查。

2vuwiymt

2vuwiymt3#

当使用@Adam Beleko的答案时,我得到了这个错误:
导出可变的“let”绑定,请改用“const”。eslintimport/no-mutable-exports错误。
为了解决这个问题,我将其更改为:const analytics = app.name && typeof window !== 'undefined' ? getAnalytics(app) : null;
您的代码中包含修改了“窗口未定义”错误的行:

import { initializeApp, getApps, getApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from 'firebase/auth'
import { getFirestore } from '@firebase/firestore'

const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
const auth = getAuth();
const db = getFirestore(app)

// try to add analytics
const analytics =
  app.name && typeof window !== 'undefined' ? getAnalytics(app) : null;

export {auth, db, analytics}

相关问题