1

我开始使用webpack-workbox-plugin注入. 我的是一个跑过来的。service workerapplicationprojectASP.NET Core web applicationIIS 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);
        });
      });
    }
}

但是当我运行时applicationclient找不到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.

有什么办法可以解决它?谢谢

4

1 回答 1

0

使用clean-webpack-plugin和解决write-file-webpack-plugin

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

但不确定这是最好的方法

于 2019-11-25T11:32:12.603 回答