联机时workbox-webpack-plugin服务工作程序不会从缓存中获取

时间:2018-10-24 13:39:47

标签: javascript service-worker workbox workbox-webpack-plugin

我有一个可以在localhost上正常运行的软件,但是无法从高速缓存中获取。像往常一样,它工作正常,但是以某种方式停止了。

文件已缓存,但请求始终进入网络。我已经检查了开发工具上的文件。

我也不确定缓存的过期设置。

您可以在线查看at this site:

以下是相关代码:

registerServiceWorker.js

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
  window.location.hostname === '[::1]' ||
  window.location.hostname.match(
    /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
  )
);

export default function register() {
  if ('serviceWorker' in navigator) {
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      return;
    }
  window.addEventListener('load', () => {
    const swUrl = `/dist/sw-dist.js`;

    if (isLocalhost) {
      checkValidServiceWorker(swUrl);
      navigator.serviceWorker.ready.then(() => {
        console.log(
          'This web app is being served cache-first by a service ' +
            'worker.'
        );
      });
    } else {
      registerValidSW(swUrl);
    }
  });
}
}

function registerValidSW(swUrl) {
navigator.serviceWorker
  .register(swUrl)
  .then(registration => {
    registration.onupdatefound = () => {
      const installingWorker = registration.installing;
      installingWorker.onstatechange = () => {
        if (installingWorker.state === 'installed') {
          registration.pushManager.subscribe({userVisibleOnly: true});
          if (navigator.serviceWorker.controller) {
            console.log('New content is available; please refresh.');
          } else {
            console.log('Content is cached for offline use.');
          }
        }
      };
    };
  })
  .catch(error => {
    console.log('error', error);
    console.error('Error during service worker registration:', error);
  });
}

function checkValidServiceWorker(swUrl) {
fetch(swUrl)
  .then(response => {
    if (
      response.status === 404 ||
      response.headers.get('content-type').indexOf('javascript') === -1
    ) {
      navigator.serviceWorker.ready.then(registration => {
        registration.unregister().then(() => {
          window.location.reload();
        });
      });
    } else {
      // Service worker found. Proceed as normal.
      registerValidSW(swUrl);
    }
  })
  .catch(() => {
    console.log(
      'No internet connection found. App is running in offline mode.'
    );
  });
}

export function unregister() {
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.ready.then(registration => {
    registration.unregister();
  });
}
}

服务工作者的分发代码如下。您可能会看到使用cacheFirst策略的在线版本,就像我都尝试过的那样。

importScripts("precache-manifest.1d6e1c2332794b82f85bd1c2e608d2b6.js", "https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js");


workbox.skipWaiting();
workbox.clientsClaim();
workbox.routing.registerRoute(
  new RegExp('/dist/img/*'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'img-cache',
    plugins: [
        new workbox.expiration.Plugin({
            maxAgeSeconds: 360 * 24 * 60 * 60,
        }),
    ],
  })
);
workbox.routing.registerRoute(
  new RegExp('/dist*'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'js-cache',
    plugins: [
        new workbox.expiration.Plugin({
            maxAgeSeconds: 30 * 24 * 60 * 60,
        }),
    ],
  })
);
workbox.routing.registerRoute(
  new RegExp('/dist/css*'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'css-cache',
    plugins: [
        new workbox.expiration.Plugin({
            maxAgeSeconds: 10 * 24 * 60 * 60,
        }),
    ],
  })
);

workbox.precaching.precacheAndRoute(self.__precacheManifest || []);

1 个答案:

答案 0 :(得分:0)

我在很多方面都错了。即使在本地主机上,也没有从缓存中获取文件。我误读了Firefox的开发工具网络标签。它可以清楚地显示文件在正常运行时是由“服务工作者”提供的。

问题在于服务工作者脚本的放置位置。应该是根源。

这是完成该任务的webpack.config.js(Webpack 4):

 const path = require('path');
 const CleanWebpackPlugin = require('clean-webpack-plugin');
 const dist = 'dist';
 const {InjectManifest} = require('workbox-webpack-plugin');


module.exports = {
mode: "production",
entry: {
    home:'./src/entry_home.js',
    rest:'./src/entry_rest.js',
    mini:'./src/entry_mini.js',
},
output: {
    //path: path.resolve(__dirname, dist),
    path: __dirname+'/dist',
    //filename: "[name].[chunkhash].soeez.js",
    filename: "[name].0211.js",
    publicPath: "/dist/"
},
externals: {
    jquery: 'jQuery'
},
module: {
    rules: [
     //{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]},
    //{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
    {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader",
        }
    },
    ]
},
optimization: {
    splitChunks: {
        cacheGroups: {
            commons: {
                name: 'common',
                chunks: 'initial',
                minChunks: 2
            }
        }
    }
},
plugins: [
    new CleanWebpackPlugin([
        dist + '/*.js'
        ]),
    //new BundleAnalyzerPlugin(),
    new InjectManifest({
        swSrc: './src/sw_src.js',
        swDest: '../sw-dist.0211.js',
    }),
]

};