简体   繁体   English

如何使用Webpack将Firebase云消息传递包含到ReactJS项目中

[英]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. 我已经尝试在我的ReactJS Webpack项目中实施FCM一周了。 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. 我能够生成一个服务工作者文件,如果我是正确的话,该文件包含正确的功能,可以从云中接收Firebase通知,但是什么也没发生。 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. 我已经以多种方式进行了尝试,但是现在我陷入了一种困惑:不知道我的webpack配置是否错误,或者服务工作者文件缺少某些内容。 I have gone through all the tutorials and issues in SO and whatnot, but nothing work for me. 我已经阅读了SO等所有教程和问题,但对我没有任何帮助。

This is my webpack.config.js file: 这是我的webpack.config.js文件:

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): 我在运行网页时拥有的用于Firebase消息传递的文件(具有焦点):

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 然后我的sw.js文件

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): 最后是我的构建目录js文件夹(捆绑的源代码和serivceworker文件)中的内容的屏幕截图: 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. 我遇到各种不同的错误,一种是serviceworker文件具有不受支持的mime类型,还有一种是Firebase错误。 They look something like this in chrome console (I took some of the stuff away, this gives these basic idea): 它们在chrome控制台中看起来像这样(我拿走了一些东西,这给出了这些基本思想):

"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. 我已经尝试了几周相同的事情,发现从sw-precache-webpack-plugin'或worbox生成的webpack服务工作程序在导入脚本时遇到了问题,而GitHub问题却没有明确的解决方案,Google愚蠢的是,任何人的文档都没有,无论是初学者还是业余爱好者,他们都缺乏理解人类学习曲线的能力。 Get away from firebase as I am doing tried making my own service worker and generating them = nothing works with firebase. 我正在尝试制作自己的服务人员并生成它们,所以请远离firebase,这对于firebase无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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