我在 Firebase 上创建的 nextJS 应用程序遇到问题,按照此过程运行以下命令:
% npx create-next-app@latest
% cd myapp
% firebase experiments:enable webframeworks
% npm install -g firebase-tools
% firebase init hosting
% firebase deploy
% npm i firebase
% firebase --version
13.4.1
这是app/page.tsx的内容:
% cat app/page.tsx
import Image from "next/image";
import LoadData from './components/loadData'
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
Where shall we go ?
<LoadData/>
</main>
);
}
%
这是app/components/loadData.tsx的内容:
% cat app/components/loadData.tsx
import { useState, useEffect } from 'react';
import firebase from 'firebase/compat/app';
export default function LoadData() {
// const dbRef = firebase.database (This produces no error)
const dbRef = firebase.database()
//const dbRef = firebase.database().ref('Restaurant')//.child('Adventure')
/*dbRef.push().set({
name: 'My favorite one',
phone: '00-6969-1122',
station: '2nd Street North"'
})*/
return (
<div>
LoadData
</div>
)
} /* End of LoadData */
%
最后我有了这个文件(initFirebase.tsx):
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';
// Note about the following. To be able to log in, only the apiKey is necessary.
// The rest of the information is only useful to access the database.
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_WEB_API_KEY,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL
};
firebase.initializeApp(firebaseConfig);
export default firebase;
export {firebaseConfig}
运行此命令时:
% Firebase 部署
我得到这样的答案:
.......
TypeError: e$.database is not a function
......
> Export encountered errors on following paths:
/page: /
Error: An unexpected error has occurred.
通过做一些实验,我弄清楚了这一行:
const dbRef = firebase.database()
正在引发问题。但我真的不知道该怎么办。
任何帮助或相关提示将不胜感激。
(当然,最后我希望能够访问我的(实时)数据库进行读/写)
要初始化和使用 Firebase 产品,请创建一个目录
firebase
和一个文件 config.js
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "..."
};
const firebaseApp = initializeApp(firebaseConfig);
export const firebaseDatabase = getDatabase(firebaseApp);
在组件中,使用从
firebase/config.js
导入的 Firebase 产品实例,并从 Firebase SDK 导入所需的其他方法或模块
import { firebaseDatabase } from '../firebase/config';
import { push, ref } from "firebase/database";
export default function Home() {
const writeData = () => {
push(ref(firebaseDatabase, 'items'), {
name: "itemName"
});
}
return (
<button onClick={writeData}>Write Data</button>
)
}