Tumtin Eliezer
Tumtin Eliezer

Reputation: 63

How to setup google workbox with vue JS spa

I have an Ionic project built on VUE Js, and I am trying to configure the @vue/cli-plugin-pwa which is essentially an abstraction of google workbox.

I have created a vue.config.js file with the following content:

module.exports = {
  pwa: {
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
     swSrc: 'src/service-worker.js',
    }
  }
}

and the src/service-worker.js contents are

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

I am trying to handle "fallback responses" for when the user is offline(No internet) as mentioned here in the official docs to avoid the default "no internet" page. Unfortunately, I can not figure out how to implement it.

I have spent days trying to figure this out and have gone over the docs several times, I understand what the docs are implying but I just can't figure out how/where to implement this in VUE js. And the official Vue CLI docs on the subject (link here) are pretty much moot.

Would really appreciate it if anyone could help me out or show me some sample repos.

Upvotes: 1

Views: 3066

Answers (1)

Tumtin Eliezer
Tumtin Eliezer

Reputation: 63

After taking a few days off and looking back at it now, I have realized that the currents docs by google are for workbox version 6, and documentation for workbox version 5 is marked legacy.

Whereas the @vue/cli-plugin-pwa plugin has a dependency for workbox version 4.3, which is severely outdated; there are a lot of breaking changes and compatibility issues between the two. Given this fact and that I am short on time I started to look in a different direction.

After some trial and error, I have reverted back to the GenerateSW method as it exposes a navigateFallback option, which if set to the entry file, in my case index.html prevents the default "no internet" page in case of a refresh by the user when offline.

Additionally, I have resorted to handling the API errors in the application by intercepting the Axios calls.

If anyone is interested this is my vue.config.js:

module.exports = {
    pwa: {
        workboxPluginMode: 'GenerateSW',
        workboxOptions: {
            navigateFallback: '/index.html',
            cleanupOutdatedCaches: true,
            importWorkboxFrom: 'local',
            importScripts: ['/inject-sw.js']
        }
    }
}

I know this might not be the proper way of doing it, but this at least solves the problem for now.

If anyone has a better way of doing it, feel free to point it out.

Also, this "article" was very resourceful when I was trying to understand how it all works.

Upvotes: 3

Related Questions