So create-react-app includes service worker functionality by default, which is lovely - all my static assets get cached for offline use out of the box. Cool, but now I want to take things a bit further and use indexedDB to cache some dynamic content.
Problem is, there's no service-worker.js file to modify. It gets generated during the build process.
Is there a way to add additional logic without ejecting create-react-app or redoing all the nice static caching stuff?
As you've observed, create-react-app
's config is locked down, and the service worker logic is entirely defined in the config.
If you'd rather not eject
but you want some customization, another option is to modify the create-react-app
build process to explicitly call the sw-precache
CLI after the normal build has completed, overwriting the service-worker.js
that create-react-app
generates by default. Because this involves modifying your local package.json
, it doesn't require eject
ing first.
There's some info on this approach here, and the general idea is modifying your npm
scripts to look something like:
"build": "react-scripts build && sw-precache --config=sw-precache-config.js"
With sw-precache-config.js
configured based on your needs, but including
swFilePath: './build/service-worker.js'
to ensure that the built-in service-worker.js
is overwritten.
I had the same problem and without doing eject
, I could replace the default service-worker
with workbox
-generated one to add runtime caching webfonts, api calls, etc.
- install
workbox-build
- prepare
src/sw-template.js
to add your registerRoute
calls
- prepare
/build-sw.js
to copy workbox file to 'build' folder and injectManifest
- modify
package.json
scripts to run above build-sw.js
- modify
src/registerServiceWorker.js
to replace the default one
You can find detailed file changes here.