如何使用Webpack将Firebase云消息传递包含到ReactJS项目中 [英] How to include firebase cloud messaging into ReactJS project using webpack

查看:56
本文介绍了如何使用Webpack将Firebase云消息传递包含到ReactJS项目中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试在我的ReactJS Webpack项目中实施FCM一周了.我能够生成一个服务工作者文件,如果我是正确的话,该文件包含正确的功能,可以从云中接收Firebase通知,但是什么也没发生.我已经以多种方式尝试过此方法,但是现在我陷入了一个困惑,就是不知道我的webpack配置是否错误,或者服务工作者文件缺少某些内容.我已经阅读了SO中的所有教程和问题,但对我没有任何帮助.

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.

这是我的webpack.config.js文件:

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;

当网页运行(具有焦点)时,我有此文件用于Firebase消息传递:

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;

然后创建我的sw.js文件

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!');
}

最后是我的构建目录js文件夹(捆绑的源代码和serivceworker文件)中的内容的屏幕截图:

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

编辑. 我遇到各种不同的错误,一种是serviceworker文件具有不受支持的mime类型,还有一种是Firebase错误.在chrome控制台中,它们看起来像这样(我拿走了一些东西,这给出了这些基本思想):

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

推荐答案

我已经尝试了数周的同一件事,并且发现从sw-precache-webpack-plugin或worbox生成的webpack服务工作程序具有导入脚本的问题与GitHub的问题在没有明确的解决方案的情况下失去了GitHub一样,Google愚蠢的是,任何人的文档都不适合初学者甚至业余爱好者,因为他们缺乏理解人类学习曲线的能力.在尝试做我自己的服务人员并生成它们的过程中,请远离firebase.

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.

这篇关于如何使用Webpack将Firebase云消息传递包含到ReactJS项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆