簡體   English   中英

聯機時workbox-webpack-plugin服務工作程序不會從緩存中獲取

[英]workbox-webpack-plugin service worker does not fetch from cache when online

我有一個可以在localhost上正常運行的軟件,但是無法從緩存中在線獲取。 像往常一樣,它工作正常,但是以某種方式停止了。

文件被緩存,但是請求始終進入網絡。 我已經檢查了開發工具上的文件。

我也不確定緩存的過期設置。

您可以在以下站點在線查看它

以下是相關代碼:

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 || []);

我在很多方面都錯了。 即使在本地主機上,也沒有從緩存中獲取文件。 我誤讀了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',
    }),
]

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM