«

umi配置WorkboxPlugin, service-worker

emer 发布于 2023-8-4 18:59   1081 次阅读     


安装workbox-webpack-plugin插件
.umirc.ts 增加
import { generalWorkBoxConfig, swScript } from './config/config';
  chainWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      generalWorkBoxConfig(config);
    }
  },

headScripts: process.env.NODE_ENV === 'production' ? [swScript] : [],


config.js配置如下:

import { GenerateSW } from 'workbox-webpack-plugin';

export const swScript = `
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js').then(registration => {
        console.log('SW registered: ', registration);
        }).catch(registrationError => {
        console.log('SW registration failed: ', registrationError);
        });
    });
}
`;

export function generalWorkBoxConfig(config) {
  config.plugin('WorkboxPlugin').use(GenerateSW, [
    {
      cacheId: 'removebg-sw',
      clientsClaim: true,
      skipWaiting: true,
      maximumFileSizeToCacheInBytes: 1,
      cleanupOutdatedCaches: true,
      runtimeCaching: [
        {
          urlPattern: ({ request }) => {
            const domain = new URL(request.url).host
              .split('.')
              .slice(-2)
              .join('.');
            let flag = false;
            let suffixArr = ['.onnx', '.wasm'];
            for (let suffix of suffixArr) {
              if (request.url.includes(suffix)) {
                flag = true;
                break;
              }
            }

            return domain === 'lininn.cn' && flag;
          },
          // handler: 'StaleWhileRevalidate',
          handler: 'CacheFirst',
        },
      ],
    },
  ]);
}