首页 > 解决方案 > 在 webpack 中注册一个 service worker

问题描述

我使用 webpack 来构建我的 React 应用程序。我不明白如何为我的服务人员指路。在index.js文件中,我成功收到一条注册消息,但是我无法访问 service worker 的文件public/serviceWorker.js

WebPack 配置

 plugins: [
    new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'public/index.html',
        favicon: 'public/favicon.ico'
    }),
    new MiniCssExtractPlugin({
        filename: 'style.css'
    }),
    new WorkboxPlugin.GenerateSW({
        swDest: path.join(__dirname, 'build/serviceWorker.js'),
        clientsClaim: true,
        skipWaiting: true
    })
],

index.js

  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('serviceWorker.js')
            .then((registration) => {
                registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: convertedVapidKey
                })
                    .then((subscription) => {
                        sendSubscriptionToServer(subscription)
                    })
                    .catch((error) => {
                        console.log(error)
                    })
            })
            .catch((error) => {
                console.log(error);
            })
    })
}

标签: javascriptreactjswebpackservice-worker

解决方案


推荐阅读