首页 > 解决方案 > 如何避免使用 webpack 和 workbox 调用陈旧的块?

问题描述

我正在尝试了解使用 Workbox 和 Webpack 的服务人员。

我已经将我的 webpack 配置设置为使用带有 chunkhash 作为名称的块。我还设置了 Workbox 来为我生成 SW。然而,问题是每次我重建我的应用程序并发布它时,当用户调用一个已更改的块时,他们得到了死亡加载器并且没有加载任何内容。我确实使用 CleanWebpackPlugin 在每次构建之前清理我的 dist 文件夹。

我相信这是因为 SW 仍在使用旧哈希名调用旧块,并且它不再存在。当我关闭应用程序并从头开始重新加载它时,它会神奇地工作。

我知道软件在他们的逻辑中有这种“延迟”,它将在下一次加载时起作用。但我需要处理不存在的旧哈希块的实例。

  1. 我应该保留旧的、过时的块吗?如果是这样,有没有办法我可以使用时间戳而不是 chunkhash 名称,所以我会知道哪些已经更新,并且可以在一定时间后删除旧的?仍然不确定这是否会解决用户的问题。
  2. 我根本不应该使用 chunkhash 名称吗?
  3. 有没有办法强制服务工作者在调用块之前检查更新?如果有更新,使用它,否则使用缓存的?这会让我的速度太慢吗?
  4. 最后,有没有办法告诉用户“新版本可用”。我真的不想这样做,因为这会很烦人,因为我处于早期阶段并且经常发布。

我在这里发布我的相关 webpack 片段:

module.exports = {
  entry: {
      app: './src/index.js'
  },
  output: {
      filename: '[name].[chunkhash:4].js',
      chunkFilename: '[name].[chunkhash:4].js', //name of non-entry chunk files
      path: path.resolve(__dirname, 'dist'),  //where to put the bundles
      publicPath: "/" // This is used to generate URLs to e.g. images
        },

...

plugins: [
    new CleanWebpackPlugin(['dist']),
    new CopyWebpackPlugin([ { from: __dirname + '/public', to: __dirname + '/dist/public' } ]),
    new MiniCssExtractPlugin({filename: "[name].css"}),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
       "template": "./src/template.html",
       "filename": "index.html",
       "hash": false,
       "inject": true,
       "compile": true,
       "favicon": false,
       "minify": true,
       "cache": true,
       "showErrors": true,
       "chunks": "all",
       "excludeChunks": [],
       "title": "ShareWalks",
       "xhtml": true,
       "chunksSortMode": 'none' //fixes bug
       })
   ]

工作箱片:

 module.exports = merge(common, {
   mode: 'production',
   devtool: 'source-map',
   plugins: [
          new WorkboxPlugin.GenerateSW({ 
          // these options encourage the ServiceWorkers to get in there fast     
           // and not allow any straggling "old" SWs to hang around     
           clientsClaim: true,     
           skipWaiting: true
      }),
   ]
});

标签: webpackservice-workerworkbox-webpack-plugin

解决方案


推荐阅读