简体   繁体   中英

How to include firebase cloud messaging into ReactJS project using webpack

I have tried to implement FCM for a week now into my ReactJS Webpack project. I am able to generate a service worker file, which if I am correct, contains the correct functions to receive firebase notifications from the cloud, but nothing happens. I have tried this in many ways, and now I'm stuck in between not knowing if my webpack configuration is wrong, or that the service worker file is missing something. I have gone through all the tutorials and issues in SO and whatnot, but nothing work for me.

This is my webpack.config.js file:

var path = require('path');
var util = require('util');
var autoprefixer = require('autoprefixer-core');
var pkg = require('../package.json');
var merge = require('webpack-merge');

var loaders = require('./loaders');
var plugins = require('./plugins');

var DEBUG = process.env.NODE_ENV === 'development';
var TEST = process.env.NODE_ENV === 'test';

var jsBundle = path.join('js', util.format('[name].%s.js', pkg.version));

var entry = {
  app: ['whatwg-fetch', './app.jsx'],
  sw: ['../app/sw.js']
};

if (DEBUG) {
  entry.app.push(
    util.format(
      'webpack-dev-server/client?http://%s:%d',
      pkg.config.devHost,
      pkg.config.devPort
    )
  );
  entry.app.push('webpack/hot/dev-server');
}

var common = {
  entry: entry,
  output: {
    path: path.resolve(pkg.config.buildDir),
    publicPath: '/',
    filename: jsBundle,
    pathinfo: false
  }
};

var config;

switch (process.env.NODE_ENV) {
  case 'production':
  config = merge(
    common, {
      externals: {
        'bootstrap': 'bootstrap',
        'font-awesome': 'font-awesome',
        'material-design-icons': 'material-design-icons'
      },
      context: path.join(__dirname, '../app'),
      target: 'web',
      devtool: false,
      entry: entry,
      output: {
        path: path.resolve(pkg.config.buildDir),
        publicPath: '/',
        filename: path.join('js', util.format('[name].[hash].%s.js', pkg.version)),
        pathinfo: false
      },
      module: {
        loaders: loaders
      },
      postcss: [
        autoprefixer
      ],
      plugins: plugins,
      resolve: {
        extensions: ['', '.js', '.json', '.jsx']
      }
    }
  );
  break;
  case 'development':
  console.log(entry);
  console.log(jsBundle);
  config = merge(
    common, {
      context: path.join(__dirname, '../app'),
      cache: DEBUG,
      debug: DEBUG,
      target: 'web',
      devtool: DEBUG || TEST ? 'inline-source-map' : false,
      entry: entry,
      output: {
        path: path.resolve(pkg.config.buildDir),
        publicPath: 'http://localhost:8000/',
        filename: jsBundle,
        pathinfo: false
      },
      module: {
        loaders: loaders
      },
      postcss: [
        autoprefixer
      ],
      plugins: plugins,
      resolve: {
        extensions: ['', '.js', '.json', '.jsx']
      },
      devServer: {
        contentBase: path.resolve(pkg.config.buildDir),
        hot: true,
        noInfo: false,
        inline: true,
        stats: { colors: true },
        disableHostCheck: true,
        watchOptions: {
          aggregateTimeout: 300,
          poll: 1000 // is this the same as specifying --watch-poll?
        },
        historyApiFallback: true,
        proxy: [{}] I have some proxies here
      }
    }
  );
  break;
}

module.exports = config;

This file I have for firebase messaging when webpage is running (has focus):

import * as firebase from 'firebase';
const messaging = {};

if ('serviceWorker' in navigator) {
  console.log('Service worker supported!');
  if(firebase.apps.length < 1) {
    var config = {
      apiKey: '***********************',
      authDomain: '*****.firebaseapp.com',
      databaseURL: 'https://*****.firebaseio.com',
      projectId: '*****',
      storageBucket: '*****.appspot.com',
      messagingSenderId: '*****'
    };
    firebase.initializeApp(config);
  }

  messaging = firebase.messaging();
  navigator.serviceWorker.register('js/sw.js').then(function(registration) {
    messaging.useServiceWorker(registration);
  }).catch(function(err) {
    console.log(err);
  });

  messaging.onMessage(function(payload) {
    console.log('Message received. ', payload);
  });

} else {
  console.log('Service worker not supported!');
}

export default messaging;

Then my sw.js file

import * as firebase from 'firebase';
const messaging = {};

if ('serviceWorker' in navigator) {
  console.log('Service worker supported!');
  if(firebase.apps.length < 1) {
    var config = {
      apiKey: '***********************',
      authDomain: '*****.firebaseapp.com',
      databaseURL: 'https://*****.firebaseio.com',
      projectId: '*****',
      storageBucket: '*****.appspot.com',
      messagingSenderId: '*****'
    };
    firebase.initializeApp(config);
  }

  messaging = firebase.messaging();
  navigator.serviceWorker.register('js/sw.js').then(function(registration) {
    messaging.useServiceWorker(registration);
  }).catch(function(err) {
    console.log(err);
  });

  messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[sw.js] Received background message ', payload);
  });
} else {
  console.log('Service worker not supported!');
}

And last a screenshot of whats in my build directory js folder (the bundled source code and serivceworker file): build_js

EDIT. I am getting all sorts of different errors, one is that the serviceworker file has unsupproted mime type, and also one firebase error. They look something like this in chrome console (I took some of the stuff away, this gives these basic idea):

"sw.fdf7b8aa233366ebfb8e.1.1.1.js:5 Uncaught e"
"FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw)
app.fdf7b8aa233366ebfb8e.1.1.1.js:28
The script has an unsupported MIME type ('text/html').
/js/sw.js Failed to load resource: net::ERR_INSECURE_RESPONSE

I have tried the same thing for weeks now and from what I have found is that webpack service workers generated by sw-precache-webpack-plugin' or worbox have issues with importing scripts lost of GitHub issues on the same with no clear resolution, Google is stupid there documentation on anything for anyone is not for beginners or even amateurs they lack the ability to understand the human learning curve. Get away from firebase as I am doing tried making my own service worker and generating them = nothing works with firebase.

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