Workbox Webpack 插件和 Webpack Dev Server 问题

Workbox Webpack Plugin and Webpack Dev Server issue

我开始使用 webpack-workbox-pluginservice worker 注入 application。我的 projectASP.NET Core web application 运行 超过 IIS Express

这是我的开发webpack config file:

const MODULE_BUILD_DIR = path.resolve(__dirname, './wwwroot/dist/assets/');
const workboxPlugin = require('workbox-webpack-plugin');

process.env.NODE_ENV = "development";

const config = {
    mode: "development",
    target: "web",
    devtool: "cheap-module-source-map",
    context: __dirname, // string (absolute path!)
    entry: [
        '@babel/polyfill',
        'font-awesome/scss/font-awesome.scss',
        './wwwroot/js/main.js',
    ],
    output: {
        path: MODULE_BUILD_DIR,
        filename: '[name].bundle.js',
        chunkFilename: '[id].chunk.js',
    },

// ...

  plugins: [
    // ...
    new workboxPlugin.GenerateSW({
      swDest: 'sw.js',
      clientsClaim: true,
      skipWaiting: true,
    }),
  ],
  devServer: {
      contentBase: path.resolve(__dirname, './'),
      historyApiFallback: false,
      inline: true,
      open: false,
      port: 9099,
      hot: true,
      https: true,
  },

// ...

}

这是我调用 main.js:

的函数
export default function setServiceWorker() {
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js').then((registration) => {
          console.log('SW registered: ', registration);
        }).catch((registrationError) => {
          console.log('SW registration failed: ', registrationError);
        });
      });
    }
}

但是当我 运行 application 时,client 找不到 sw.js 文件,因为它分配在 webpack dev server path,所以不在 [=25] =].

DevTool 封邮件:

A bad HTTP response code (500) was received when fetching the script.
---
SW registration failed:  TypeError: Failed to register a ServiceWorker
for scope ('https://localhost:44357/') with script ('https://localhost:44357/sw.js'):
A bad HTTP response code (500) was received when fetching the script.

有什么解决方案? 谢谢

使用clean-webpack-pluginwrite-file-webpack-plugin解决:

plugins: [
    new CleanWebpackPlugin(),
    new WorkboxPlugin.GenerateSW({
        swDest: 'sw.js',
        clientsClaim: true,
        skipWaiting: true,
    }),
    new WriteFilePlugin(),
],

但不确定这是最好的方法