Search code examples
reactjscreate-react-appservice-workerworkbox-webpack-plugin

How to configre Create React Apps default Service Worker to cache assets that are not in react src Context (public Folder)?


today I tried the ServiceWorker of Create React App and everything is cached except the Favicon of my Page which is defined in public/img/favicon.ico, so when the Page is Offline the Favicon disapears and Connection Error is displayed in Console, so does anyone has experience how to configure webpage Plugin of the Service worker to cache this too?


Solution

  • I have a CRA project here. I don't precache my favicon, I let a default handler runtime cache it, but I do precache a fallback image and you should be able to do the same to precache your favicon.

    CRA creates a default sw which I don't think I touched. To get more control I use workbox in a sw-addendum file that I append to the default sw in the build. In the addendum you can precache what you need and set up routes, etc.

    see package.json for postdeploy script

    "postdeploy": "cp src/face.69232788.jpg docs/face.69232788.jpg && cat src/swAddendum.js >> docs/service-worker.js",
    

    sw-addendum here

    workbox.precaching.precache([
      './face.69232788.jpg',
    ]);