简体   繁体   中英

How to bundle firebase-messaging-sw.ts in NextJS

How to use Firebase Messaging Service Worker ( firebase-messaging-sw.ts ) with NextJS? I see in the documentation that I must use bundler to use Modular Version 9 , otherwise the first two lines of the code from documentation will throw an error "Cannot use import outside a module"

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

You are able to configure Webpack in NextJS

You are able to configure Webpack in NextJS by using next.config.js file located at the root of your NextJS project directory.

module.exports = {
  distDir: 'app',
  strictMode: false,
  
  webpack: (config) => {
    // Modify config
    return config;
  },
};

Add firebase-messaging-sw.ts to webpack entries

module.exports = {
  distDir: 'app',
  strictMode: false,
  
  webpack: (config) => {
    // Add firebase-messaging-sw.ts to webpack entries
    config.entry = async () => {
      const oldEntries = await oldEntriesPromise;
      return {
        ...oldEntries,
        "firebase-messaging-sw": {
          import: './src/firebase-messaging-sw.ts',
          filename: './public/firebase-messaging-sw.js',
        }
      }
    };

    return config;
  },
};

Content of my firebase-messaging-sw.ts

declare const self: ServiceWorkerGlobalScope;

const { initializeApp } = require("firebase/app");
const { getMessaging, onBackgroundMessage } = require("firebase/messaging/sw");

// How to get firebaseConfig of your firebase project - https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
  measurementId: '',
};

const firebaseApp = initializeApp(firebaseConfig);

const messaging = getMessaging(firebaseApp);

onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

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

export {};

Source: How to add Webpack entry to NextJS project?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM