blankface
blankface

Reputation: 6347

How to cache React application in service worker

I'm trying to create a React PWA from scratch. So far my project outputs the minified files to a dist/js folder.

In my service worker file I'm using Workbox to precache the app. This is my setting so far:

importScripts("./node_modules/workbox-sw/build/workbox-sw.js");

const staticAssets = [
    "./",
    "./images/favicon.png",
]

workbox.precaching.precacheAndRoute(staticAssets);

Currently if I enable offline from dev tools > Service Workers, it throws these errors and the app fails to load:

3localhost/:18 GET http://localhost:8080/js/app.min.js net::ERR_INTERNET_DISCONNECTED
localhost/:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
3:8080/manifest.json:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
logger.mjs:44 workbox Precaching 0 files. 2 files are already cached.
5:8080/manifest.json:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED

How can I fix this?

Upvotes: 3

Views: 4174

Answers (1)

Ashish Kamble
Ashish Kamble

Reputation: 2627

this means your resources are not getting cached properly, you need to add them to cache before accessing, workbox by default do it for you. it shows 2 files cached, as they present in your array, expected result same do it for all remaining too.

const staticAssets = [
    "./",
    "./images/favicon.png",
    "./js/app.min.js",
    "./manifest.json",
    { url: '/index.html', revision: '383676' }
]

you can try to add eventlistener,

self.addEventListener('install', event => {
  console.log('Attempting to install service worker and cache static assets');
  event.waitUntil(
    caches.open("staticCacheName")
    .then(cache => {
      return cache.addAll(staticAssets);
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(caches.match(event.request)
  .then(function(response) {
      if (response) {
        return response;
      }
      return fetch(event.request);
    })
  );
});

Upvotes: 1

Related Questions