在Webpack中注册服务人员

时间:2019-03-18 08:35:58

标签: javascript reactjs webpack service-worker

我使用webpack构建我的React应用。我不明白如何为我的服务人员指明道路。在index.js文件中,我成功收到注册消息,但是无法访问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);
            })
    })
}

0 个答案:

没有答案