Workbox-webpack-plugin 嵌套 urls sw 注册

Workbox-webpack-plugin nested urls sw registration

我在我的 React 应用程序中嵌套了路由,比如 https://my-app.com/someroute/new and on https://my-app.com/someroute level service worker registration works fine, but on https://my-app.com/someroute/new 级别它失败了

Error during service worker registration: DOMException: Failed to register a ServiceWorker for scope ('https://my-app.com/someroute/') with script ('https://my-app.com/someroute/service-worker.js'): The script has an unsupported MIME type ('text/html').

我尝试将 directoryIndex 设置为“../”,但也没有成功。

我的工作箱插件配置在这里:

new GenerateSW({
    cacheId: 'my-app',
    skipWaiting: true,
    clientsClaim: true,
    exclude: [/\.map$/, /^manifest.*\.js(?:on)?$/, /\.html$/],
}),

该错误意味着当您的网络应用程序从您的网络服务器请求 URL https://my-app.com/someroute/service-worker.js 时,它不会返回 service-worker.js 的 JavaScript 内容,而是返回一个HTML 文档。这大概是一个“404 未找到”错误文档,因为 Web 服务器认为 https://my-app.com/someroute/service-worker.js 不存在。

解决这个问题的方法是确保有一个有效的 service-worker.js 文件存在于您的网络服务器根目录下的 /someroute/ 目录中。

GenerateSW workbox-webpack-plugin 有一个 swDest 属性 可以用来控制服务工作文件输出的位置。将其设置为 swDest: '/someroute/service-worker.js' 可能足以解决您的问题。