我正在使用Workbox Webpack插件(v4.3.1)生成服务工作者脚本,并使用Workbox-Window(v4.3.1)插件进行注册。
在开发环境(我使用webpack开发服务器)上一切正常,但是在生产版本中,我在Chrome(v78)开发控制台上收到以下错误:
Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:4321/') with script ('http://localhost:4321/undefined'): A bad HTTP response code (404) was received when fetching the script.
(注意:我正在使用本地Nginx服务器来测试我的生产版本)
我正在像这样使用Workbox Webpack GenerateSW:
new WorkboxPlugin.GenerateSW({
clientsClaim: true,skipWaiting: false
})
我确认,在构建之后,将生成服务工作者脚本(service-worker.js),并将其保存在dist文件夹中。
我正在使用Workbox-Window插件注册上述服务工作者脚本:
import { Workbox } from 'workbox-window'
if ('serviceWorker' in navigator) {
const wb = new Workbox('/service-worker.js') // Note: I also tried without the bar and with path './service-worker.js' and didnt work
wb.register()
}
我猜测该问题与Im使用Nginx测试产品构建的事实无关,也与提供给Workbox构造函数的Service Worker脚本的url或路径无关,因为使用ServiceWorker Web API而不是Workbox Window API,效果很好:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js') // THIS WORKS!!!
}
为什么在完全相同的条件下,使用Workbox Window API的服务工作者注册失败?您可以在错误日志中看到的undefined
来自哪里?
*编辑* 我在Workbox GitHub存储库上打开了一个问题。您可以找到它here。