How to implement PWA (React, PWA, Webpack)
#react
#pwa
#webpack
1. Install node modules
First, we have to install webpack modules to build PWA
yarn add --dev webpack-pwa-manifest workbox-webpack-plugin
2. Create manifest.json file
public/manifest.json
{ "name": "react-webpack", "short_name": "react", "description": "react todo list app with pwa", "background_color": "#ffffff", "crossorigin": "use-credentials", "theme_color": "#eeeeee", "filename": "manifest.json" }
3. Implement webpack options
webpack.config.js
... const WebpackPwaManifest = require('webpack-pwa-manifest') const { GenerateSW } = require('workbox-webpack-plugin') const manifest = require('./public/manifest.json') ... const pwaPlugin = new WebpackPwaManifest(manifest) const workboxPlugin = new InjectManifest({ swSrc: './src/sw.js', swDest: 'sw.js', }) ... { ... plugins: [htmlPlugin, cssPlugin, pwaPlugin, workboxPlugin], }
src/sw.js
workbox.core.skipWaiting() workbox.core.clientsClaim() workbox.routing.registerRoute( new RegExp('<https://jsonplaceholder.typicode.com>'), new workbox.strategies.StaleWhileRevalidate() ) self.addEventListener('push', event => { const title = 'Get Started With Workbox' const options = { body: event.data.text(), } event.waitUntil( self.ServiceWorkerRegistration.showNotification(title, options) ) }) workbox.precaching.precacheAndRoute(self.__precacheManifest)
We’ve implemented manifest file and service worker settings.
4. Implement service worker
src/index.js
import React from 'react' import ReactDOM from 'react-dom' import Root from './components/Root' import './styles/index.scss' ReactDOM.render(<Root />, document.getElementById('root')) if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker .register('/sw.js') .then(registration => { console.log('SW registered', registration) registration.pushManager.subscribe({ userVisibleOnly: true }) Notification.requestPermission().then(p => { console.log(p) }) }) .catch(e => { console.log('SW registration failed: ', e) }) }) }
After you’ve implemented above
index.js
, you can see Service Worker is running on the developer settings panel (of browser). (Click the Application tab, and click Service Workers tab)Also, if you are in offline mode, you can see offline web app is working properly after you refresh your browser!
That’s because we’ve added
json placeholder url
on runtTimeCaching
option.Finally, we can see push notifications are working.
You can test on Application tab’s Service Workers. (You can click push button.)