Next Js 找不到Service messaging (firebase-cloud-messaging)

Next Js cant find Service messaging (firebase-cloud-messaging)

您好,我在下一个 js 项目中使用 firebase 云消息传递,当我尝试 运行 或构建我的项目时,我收到此错误:

信息 - 检查类型的有效性
信息 - 创建优化的生产版本
信息 - 编译成功 信息 - 收集页面数据 ...node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^

错误:服务消息不可用 在 Provider.getImmediate (文件:///I:/Work/Web/Php/Project/wamp/www/test/node_modules/@firebase/component/dist/esm/index.esm2017.js:147:23) 在 getMessagingInWindow (I:\Work\Web\Php\Project\wamp\www\test\node_modules@firebase\messaging\dist\index.cjs.js:1460:74) 在我:\Work\Web\Php\Project\wamp\www\test.next\server\pages_app.js:117:83 { 类型:'Error' }

我的代码: 似乎这个问题发生是因为使用 getMessaging

firbase.js

import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from "firebase/messaging";

var firebaseConfig = {
    apiKey: "----",
    authDomain: "---",
    projectId: "---",
    storageBucket: "---",
    messagingSenderId: "---",
    appId: "---",
    measurementId: "---"
};

const firebaseApp = initializeApp(firebaseConfig);
const messaging =  getMessaging(firebaseApp);

export const fetchToken = (setTokenFound) => {
    return getToken(messaging, {vapidKey: '---'}).then((currentToken) => {
        if (currentToken) {
            console.log('current token for client: ', currentToken);
            setTokenFound(true);
            // Track the token -> client mapping, by sending to backend server
            // show on the UI that permission is secured
        } else {
            console.log('No registration token available. Request permission to generate one.');
            setTokenFound(false);
            // shows on the UI that permission is required
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
        // catch error while creating client token
    });
}

export const onMessageListener = () =>
    new Promise((resolve) => {
        onMessage(messaging, (payload) => {
            resolve(payload);
        });
    });

firebase-消息传递-sw.js

// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
     apiKey: "----",
    authDomain: "---",
    projectId: "---",
    storageBucket: "---",
    messagingSenderId: "---",
    appId: "---",
    measurementId: "---"
};

firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
    console.log('Received background message ', payload);

    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
    };

    self.registration.showNotification(notificationTitle,
        notificationOptions);
});

_app.tsx

import {fetchToken,onMessageListener} from '../tools/firebase'
    const [notification, setNotification] = useState({title: '', body: ''});
  const [isTokenFound, setTokenFound] = useState(false);
useEffect(() => {
        fetchToken(setTokenFound)
        onMessageListener().then(payload => {
            setNotification({title: payload.notification.title, body: payload.notification.body})

            console.log(payload);
        }).catch(err => console.log('failed: ', err));

    }, []);

我有同样的问题原来是 firebase v9 问题

使用 firebase v8 对我有用

npm i firebase@8.2.3

安装 v8 后不要忘记更改语法 firebase.initializeApp(firebaseConfig);