Reputation: 101
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?
Upvotes: 10
Views: 3258
Reputation: 1416
Good news in version 4!:
Starting with Create React App 4, you have full control over customizing the logic in this service worker, by creating your own src/service-worker.js file, or customizing the one added by the cra-template-pwa (or cra-template-pwa-typescript) template.
(https://create-react-app.dev/docs/making-a-progressive-web-app/)
Upvotes: 0
Reputation: 89
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.
Upvotes: 2
Reputation: 856
I've done it without eject
You can place your workers in the public
folder, then you'd have to transpile and minify them by yourself.
As discussed in here https://github.com/facebook/create-react-app/issues/1277
Upvotes: 0