如何将 background-sync-plugin 添加到 workbox-build

How to add background-sync-plugin to workbox-build

我对 workbox 和 create-react-app v2 有疑问。 我正在使用 workbox-build 来生成自定义服务工作者,并且注入有问题

const backgroundSync = new workbox.backgroundSync.Plugin('ticketsQueue', {
  maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
});


const buildSW = () =>
  workboxBuild.generateSW({
    globDirectory: 'build',
   // importWorkboxFrom: 'local',
    globPatterns: ['**/*.{json,ico,html,js,css,woff2,woff,png,svg}'],
    globIgnores: ['asset-manifest.json'],
    skipWaiting: true,
    clientsClaim: true,
    swDest: 'build/sw.js',
    navigateFallback: 'index.html',
    directoryIndex: 'index.html',
    runtimeCaching: [
      {
        urlPattern: new RegExp(`^${apiUrl}/tickets/create`),
        handler: 'networkOnly',
        options: {
          plugins: [
            backgroundSync
          ]
        },
        method: 'POST'
      },
     ]
  });

buildSW();

当我也尝试使用 nodejs 执行 buildSW() 时,它给出了一个引用错误。 ReferenceError:未定义工作箱 如何包含它?或者还有其他办法吗? 谢谢

有几个选项。

首先,您可以切换到使用 injectManifest mode,并完全控制您的服务工作者,依靠构建工具将文件数组注入预缓存。

其次,有一个快捷方式options 属性 可以简化后台同步插件的添加。配置看起来像:

runtimeCaching: [{
  // Match any same-origin request that contains 'api'.
  urlPattern: /api/,
  handler: 'networkOnly',
  options: {
    backgroundSync: {
      name: 'my-queue-name',
      options: {
        maxRetentionTime: 60 * 60,
      },
    },
  },
}]

好吧,在尝试了 url 模式之后,我意识到这是我犯了错误的地方。一个修复,在 URL 模式中,我看到 indexeddb 队列被创建并且后台同步开始按预期发生。非常感谢