Workbox Webpack插件和Webpack开发服务器问题

问题描述 投票:1回答:1

我开始使用webpack-workbox-pluginservice worker注入application。我的project是在ASP.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上分配的,因此不在IIS Express app path中。

[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.

有什么解决方案?谢谢

asp.net-core webpack-dev-server iis-express workbox-webpack-plugin
1个回答
0
投票

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

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

但不确定这是最好的方法

© www.soinside.com 2019 - 2024. All rights reserved.