I have an existing app I'm trying to convert to use React. I've copied its functionality with a brand new create-react-app
one (using react-scripts
1.0.13).
I want to use the existing service worker I have. I've noticed CRA creates its own service worker; there is code in the webpack config (using SWPrecacheWebpackPlugin
) that creates an unbundled module, service-worker.js
. All other JS modules are bundled together.
From what I understand, I can't just copy my existing service worker existing-service-worker.js
and try to import that, as all JS modules are bundled together.
I don't want to eject.
I've forked create-react-app
in order to customise react-scripts
and use different logic in the webpack config, which will allow me to use my existing service worker instead of the one it creates with SWPrecacheWebpackPlugin
... However, I don't know how to do this. This is my first time using React and webpack.
Can someone point me in the right direction, and help me use my existing service worker in React, without ejecting?
There is an npm library specifically built for this use case. Its called cra-append-sw .
Most of the details are in the npm page, but simply put you just need to install the library (npm i --save cra-append-sw).
Make a few changes to your package.json:
"start": "react-scripts start && cra-append-sw --mode dev ./public/custom-sw-import.js",
"build": "react-scripts build && cra-append-sw --skip-compile ./public/custom-sw-import.js"
And finally create a file in your public folder called custom-sw-import.js and all of the service worker code you write there will simply be appended to cra's service worker.
I can verify this works since I applied the same principle to make my website www.futurist-invenzium.com which gives a demo of all the features provided by PWA's.
I also found this blogpost to be helpful if you want a more in depth answer.
here is another solution without Ejecting:
https://medium.freecodecamp.org/how-to-build-a-pwa-with-create-react-app-and-custom-service-workers-376bd1fdc6d3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With