0

我正在使用具有以下配置的 workbox-webpack-plugin。

new WorkboxPlugin.GenerateSW({
      globDirectory: outputDir,
      globPatterns: ['**/*.{html,js}'],
      swDest: path.join(outputDir, 'sw.js'),
      clientsClaim: true,
      skipWaiting: true,
      runtimeCaching: [
        {
          urlPattern: new RegExp('cdn.test.com/'),
          handler: 'CacheFirst'
        }
      ]
    })

这可以正确构建。但问题是加载sw.js文件。我有一个自定义路径(https://test.com/custom/),而不是直接指向域(https://test.com)。构建后,sw.js 尝试加载的路径是通过https://test.com/sw.js而不是我的整个应用程序构建所在的https://test.com/custom/sw.js 。这也是我output.publicPath的 webpack 中提到的路径。如何在 Workbox 插件配置中进行设置?我正在使用"3.0.0-beta.2"版本。

4

1 回答 1

0

刚刚意识到我需要在我的应用程序中注册服务工作者,我可以在其中提及路径。

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/custom/sw.js').then(registration => {
      console.log('SW registered: ', registration);
    }).catch(registrationError => {
      console.log('SW registration failed: ', registrationError);
    });
  });
}

解决了问题

于 2018-03-29T12:08:24.127 回答