【问题标题】:Workbox Webpack Plugin and Webpack Dev Server issueWorkbox Webpack 插件和 Webpack 开发服务器问题
【发布时间】:2020-03-19 20:53:55
【问题描述】:

我开始使用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.

有什么办法可以解决这个问题? 谢谢

【问题讨论】:

  • 您好!请添加您的解决方案作为答案,而不是编辑问题,这将有助于 SO 的组织。 (如果我没记错的话,你也可以在 48 小时后接受你的答案)

标签: asp.net-core webpack-dev-server iis-express workbox-webpack-plugin


【解决方案1】:

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

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

但不确定这是最好的方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-14
    • 2016-12-17
    • 1970-01-01
    • 2021-10-31
    • 2022-11-04
    • 2016-06-26
    • 2018-08-06
    • 2016-11-20
    相关资源
    最近更新 更多