Some initial considerations:
"react": "^16.8.2",
"react-scripts": "2.1.5"
I have created a new react app and I need to implement Push Notifications. Following this tutorial, I was able to get up and running in 5 minutes, but now I have to implement the same strategy (kinda) into a react app.
The problem I am facing is that I am able to subscribe to the Notification API, but I'm not sure how to edit the service-worker.js
file to add an event listener to catch the push
event (Handle a Push Event
chapter in the google guide)
Customizing your service worker with Create React App is possible, but could be quite difficult and hacky.
Out of the box, CRA uses Workbox GenerateSW webpack plugin to generate
service-worker.js
file, and you cannot inject any code to it (you could with CRA@1, not any more with since CRA@2)You have several strategies, I'll start with the simplest one.
Solution 1: provide your own service-worker file
src/index.js
enable service worker:in
src/serviceWorker.js
register your custom file:You have to change the name cause when running dev server, CRA provides a mock for
service-worker.js
in
public/
folder, createcustom-service-worker.js
file. Webpack will copy it as is in thebuild/
folderPros: quick, dirty win
Cons: your custom file is not processed with Webpack (no imports), and you must implement the network caching logic by yourself (assuming you want a PWA) since you're bypassing Workbox plugins
Solution 2: append your code to generated service-worker
There's a module for it: cra-append-sw. You're in charge to provide the appended code.
Pros: easy setup, takes advantages GenerateSW
Cons: appended code is processed with Babel/Webpack, but not using CRA's config (you could opt-out). Still use GenerateSW which handle network caching for you. Not sure it works when developing locally
Solution 3: use Workbox in custom service-worker file
apply the first 2 steps of solution #1: change
src/index.js
andsrc/serviceWorker.js
in
src/
folder, createcustom-service-worker.js
file. It will be processed by Webpack, so you can use ES2016/TypeScript syntax and import modulesinstall react-app-rewire:
npm add --save-dev react-app-rewired
package.json
, in"scripts"
, replacereact-scripts
withreact-app-rewired
tweak webpack configuration: create
config-overrides.js
in root folder:Pros: you can use ES2016/TypeScript code in service-worker file. You still benefit from Workbox network caching facilities, with total control on it
Cons: complicated and fragile, because of the multiple configuration hack.
I've used the last solution, cause I needed both caching code from Workbox and some
import
in my service worker file.react-app-rewire-workbox may help simplifying the Webpack configuration (the one for main app). To be tested.