workbox-webpack-plugin
在我当前使用带有 ( ) 和工作箱 ( )的 webpack 的项目中,workbox-window
我遇到了一个错误,当页面加载到“深层 url”时,服务工作者将永远不会响应消息,例如“/my-path/is-nested” . 它将在“/my-path”上工作。
在最小的可重现环境中,这应该会发生。
- 在新选项卡中,访问应用程序(例如通过
https://my-app.my-name.company-dev-envs.cloud/some-unique-id
) - ServiceWorker 通过 workbox (
.register()
)注册 - 注册时,
messageSW
用于询问软件的“版本” - ServiceWorker 使用
event.ports[0].postMessage
指示版本的字符串进行响应
如果站点在“深层”路径中访问,例如 /some-unique-id/test,消息传递将永远无法工作。
Workbox 确实成功地“注册”了——但不会触发任何事件(除非externalactivated
在Update on Reload
Application > Service Worker 选项卡中选择了)Serviceworker 将被报告为“活动且正在运行”,而不会显示其他服务工作者。它似乎也可以处理获取。只有消息和事件永远不会通过wb
Workbox Window 实例响应/触发。
index.js(应用程序的主要入口)
/* globals window, System */
import './offline';
// [...]
离线.js
import { Workbox } from 'workbox-window';
if ('serviceWorker' in navigator) {
const wb = new Workbox('./sw.js');
const attachDebugEventHandlers = (events) => {
events.forEach((eventName) => {
wb.addEventListener(eventName, () => {
console.log(`[workbox sw] ${eventName} triggered`);
});
});
};
attachDebugEventHandlers([
'activated',
'controlling',
'externalactivated',
'externalinstalling',
'externalwaiting',
'installed',
'message',
'redundant',
'waiting',
]);
wb.register()
.then((registration) => {
console.log('workbox sw register successful');
console.log("sending message")
wb.messageSW({ type: 'GET_VERSION' }).then((ver) => console.log(`[workbox sw] version reported as ${ver}`))
})
.catch((err) => {
console.error('[workbox sw] could not activate sw', err);
});
sw.js
const SW_VERSION = '1.0.0';
console.log("sw loaded")
import {createHandlerBoundToURL, precacheAndRoute} from 'workbox-precaching';
import { NavigationRoute, registerRoute } from 'workbox-routing'
// auto generate from webpack manifest
precacheAndRoute(self.__WB_MANIFEST, {
// Ignore all URL parameters.
ignoreURLParametersMatching: [/.*/] // main.js is loaded with a version hash
});
self.addEventListener('message', event => {
console.log(`[Message] event: `, event.data);
});
self.addEventListener('install', function(event) {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim())
})
addEventListener('message', (event) => {
console.log("message")
if (event.data && event.data.type) {
if (event.data.type === 'GET_VERSION') {
event.ports[0].postMessage(SW_VERSION);
}
}
})
const handler = createHandlerBoundToURL('/index.html');
const navigationRoute = new NavigationRoute(handler);
registerRoute(navigationRoute);
webpack.config.js(为简洁起见)
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin');
module.exports = {
devtool: 'eval-source-map',
module: {
rules: [
{
test: /\.(jsx?)$/,
include: [
path.resolve(__dirname, 'src'),
],
use: ['babel-loader'],
},
// [...] (style loading)
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
],
},
devServer: {
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
// [...]
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/html/index.html')
}),
// [...]
new WorkboxPlugin.InjectManifest({
swSrc: './src/sw.js',
swDest: 'sw.js',
maximumFileSizeToCacheInBytes: 12 * 1024 * 1024,
}),
],
};
使用的版本:
"webpack": "^4.33.0",
"webpack-cli": "^3.3.2",
"workbox-window": "^5.1.3"
"workbox-webpack-plugin": "^5.1.3"