使用工作箱时无法访问除“ /”以外的任何页面

时间:2019-08-18 06:14:55

标签: javascript reactjs webpack service-worker workbox

当我将workbox与react-app-rewired一起使用时,在生产环境中,我无法访问除“ /”以外的任何页面。

我正在使用react-app-wired

进行构建

config.override.js

   const workboxPlugin = require('workbox-webpack-plugin')
const path = require('path')

module.exports = {
  webpack: function (config, env) {
    if (env === 'production') {
      const workboxConfigProd = {
        swSrc: path.join(__dirname, 'public', 'custom-service-worker.js'),
        swDest: 'custom-service-worker.js',
        importWorkboxFrom: 'disabled',
      }
      config = removeSWPrecachePlugin(config)
      config.plugins.push(new workboxPlugin.InjectManifest(workboxConfigProd))
    }
    return config
  }
}

function removeSWPrecachePlugin(config) {
  const swPrecachePluginIndex = config.plugins.findIndex((element) => {
    return element.constructor.name === 'SWPrecacheWebpackPlugin'
  })
  if (swPrecachePluginIndex !== -1) {
    config.plugins.splice(swPrecachePluginIndex, 1)
  }
  return config
}

custom-service-worker.js

 importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded ?`);
} else {
  console.log(`Boo! Workbox didn't load ?`);
}

workbox.core.clientsClaim();

const bgSyncPlugin = new workbox.backgroundSync.Plugin('todoQueue', {
  maxRetentionTime: 24 * 60
});

workbox.routing.registerRoute(
  /\.(?:js|css|html)$/,
  workbox.strategies.networkFirst()
);

workbox.routing.registerRoute(
  /\.(?:png|jpeg|svg|jpg)$/,
  new workbox.strategies.CacheFirst()
);

workbox.routing.registerRoute(
  new RegExp('/'),
  workbox.strategies.networkFirst()
);

如果有解决方案,我很乐意尝试

0 个答案:

没有答案