【问题标题】:workbox-webpack-plugin service worker does not fetch from cache when online在线时 workbox-webpack-plugin 服务工作者不会从缓存中获取
【发布时间】:2018-11-24 02:14:38
【问题描述】:

我有一个在 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();
  });
}
}

Service Worker 的分发代码如下。您可能会看到使用 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 || []);

【问题讨论】:

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


    【解决方案1】:

    我在很多方面都错了。即使在本地主机上也没有从缓存中获取文件。我误读了 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',
        }),
    ]
    

    };

    【讨论】:

    • 你的 sw_src.js 是什么样的?
    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 2020-11-20
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多