【问题标题】:How to add background-sync-plugin to workbox-build如何将 background-sync-plugin 添加到 workbox-build
【发布时间】:2018-11-08 09:56:59
【问题描述】:

我有关于 workbox 和 create-react-app v2 的问题。 我用workbox-build生成自定义service worker,注入有问题

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:未定义工作箱 如何包含它?或者还有其他方法吗? 谢谢

【问题讨论】:

    标签: node.js service-worker create-react-app progressive-web-apps workbox


    【解决方案1】:

    有几个选项。

    首先,您可以切换到使用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,
          },
        },
      },
    }]
    

    【讨论】:

    • 感谢您的回答。上周我在文档中没有看到这个选项 :) 但是在尝试了这个之后我注意到如果你把它放在选项中,生成的 Service Worker 不会为 queueDidReplay 传递回调函数
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2021-08-02
      • 2016-05-24
      • 2020-05-05
      • 2019-08-30
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多