DEV Community

Cover image for PWA in VUE VITE
Famosa Adegbite
Famosa Adegbite

Posted on • Updated on

PWA in VUE VITE

HOW I MAKE MY PORTFOLIO WORK OFFLINE USING VITE PLUGIN PWA
Although, I have learned about PWA since 2020 and used it with regular HTML, CSS and JavaScript applications. Applied it to my VUE VITE applications took another dimension that I like to share.

For those that are hearing PWA for the first time or don’t have ideas of what it is all about!!!

What is PWA?
PWA is a Progressive Web App that makes a website look and behave like a mobile app. PWAs are built to take advantage of native mobile device features without downloading or purchasing on the play store.

Despite the behavior of PWA in app resemblance, it’s never an app but a well-structured website that can replace a mobile app, native app, and desktop site.

Major benefits of PWAs
There are several benefits of PWA but I’m going to mention a few that impress me which include short loading time, accessibility to the website in an offline mode, push notification, and home screen features that make life easier to convert my website to resemble mobile application without visiting Google Play Store or any App Store and can be assessed on all platform either windows, androids or IOs. It cut across all platforms.

SERVICE WORKER IN PWA
Service worker is a web worker written in JavaScript that allows intercepting and control of network requests and asset caching from the web browser, which means it can respond to HTTP requests of the main document, check the availability of a remote server, cache content when that server is available and serve that content later to the document. With service workers, web developers can create reliably fast web pages and offline experiences. It’s a browser feature but it doesn’t have access to the DOM, its role is different than a normal JS script. Service workers can handle push notifications and synchronize data in the background, cache or retrieve resource requests, intercept network requests and receive centralized updates independently of the document that registered them, even when that document is not loaded.

Service workers have three stages that help maintain consistency when switching among versions of service worker:

  1. Registration: It involves informing the browser location of the service worker in preparation for installation.
  2. Installation: It occurs in two ways, first when there is no service worker initially installed in the browser related to the web app, and second when there is an update to the service worker.
  3. Activation: This happened when all of the PWA’s pages are closed in order to avoid conflict between the previous version and the updated version.

Note: Only a single service worker can be active for a domain which means out of all the versions you might have due to update only one of it will be functioning. There are two ways to it, is either you are updating the service worker automatically at the background level without the awareness of the user whenever there is a new update or you inform the user of the new update and decide either to update to the new version or not. It is highly advisable to update if there is any.

MANIFEST IN PWA
PWA Manifest is a JSON file that tells the browser about your Progressive Web App and how it should behave when installed on the user’s desktop or mobile device. A typical manifest file includes the app name, the icons the app should use, and the URL that should be opened when the app is launched, among other things. For comprehensive details about manifest visit there website, it is well detailed and explanatory.

Necessary information provided includes:

  • The name of the web application
  • The short name
  • The description
  • Theme and background color
  • Links to the web app icons.
  • The display mode, which I prefer standalone

Package used: vite-plugin-pwa

Note: Different packages can be used based on how your application is set up. But for my application, I used Vite and have my vite.confige.js file where most of the configuration will occur.

Importance of using vite-plugin-pwa
It helps add PWA with almost zero configuration to existing applications and generates all the necessary files needed for PWA.

The vite-plugin-pwa will generate:

  1. Web App Manifest using the manifest plugin option and configure the Web App Manifest on the application entry point.
  2. Service worker using the strategies plugin option and generate the script to register the service worker in the browser using the injectRegister plugin option.

VITE-PLUGIN-PWA INSTALLATION USING NPM

npm i vite-plugin-pwa -D
Enter fullscreen mode Exit fullscreen mode

To confirm if the installation is successful or not, check under dev dependencies in your package.json

Fig 1.1: Shows the dev dependencies in package.json
dev dependencies

VITE-PLUGIN-PWA CONFIGURATION
Most of the configuration is going to take place in vite.config.js file.
Firstly; import the VitePWA plugin in vite config.

import { VitePWA } from 'vite-plugin-pwa'
Enter fullscreen mode Exit fullscreen mode

Secondly: put it to use in the config under plugins:

export default defineConfig({
    plugins: [
       VitePWA({
          registerType: 'autoUpdate'
        })
    ]
})
Enter fullscreen mode Exit fullscreen mode

With this simple configuration, a lot of magic have taken place. The application will be able to generate the Web App Manifest and inject it at the entry point, generate the service worker and register it in the browser.

Wait for a little, no visible changes…. Yes there won’t be any changes until you build your application using npm run build. But before doing that, let's configure all other necessary configurations.

InjectRegister Plugin Option:
This configuration helps to control how to register the service worker in my application, although the configuration is optional, but I set my injectRegister plugins to auto.

export default defineConfig({
   plugins: [
      VitePWA({
         injectRegister: 'auto'
      })
   ]
})
Enter fullscreen mode Exit fullscreen mode

There are 4 ways to do that which is:

  1. Inline method: injectRegister: 'inline' This will inject a simple register script, at the head tag of the application entry point.
<head>
  <script>
    if('serviceWorker' in navigator) {
       window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js', { scope: '/' })
      })
    }
  </script>
</head>
Enter fullscreen mode Exit fullscreen mode
  1. Script Method: injectRegister: 'script' This method will generate a registerSW.js script adding it to the head tag of the application entry point. The Head Tag:
<head>
    <script src="/registerSW.js"></script>    
</head>
Enter fullscreen mode Exit fullscreen mode

The registers.js file will contain normal service worker script.

if('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js', { scope: '/' })
    })
}
Enter fullscreen mode Exit fullscreen mode
  1. Null Method: injectRegister: null This method will do nothing but allow you to register the service worker manually.
  2. Auto Method: injectRegister: auto Which is the default method, which will normally apply script registration method.

WORKBOX:
One of the major functions of a service worker is to act as proxies intercepting requests between the browser and the server, and the ability for your application to work offline calls for proper configuration of the service worker’s precaches manifest which includes all the resources of your application.
The vite-plugin-pwa plugin uses the workbox-build node library to build the SW which by default includes the CSS, Js, and Html resources in the manifest precache. If there is any need to add other resource types like [ico, JSON, png, SVG, and more] you will need to add them manually to the globPatterns of workbox configuration.

workbox: {
   globPatterns: ['**/*.{js,css,html,ico,png,svg,json,vue,txt,woff2}']
},
Enter fullscreen mode Exit fullscreen mode

MANIFEST
As discussed earlier, a web app manifest is a JSON file that tells the browser about your Progressive Web App and how it should behave when installed on the user's desktop or mobile device.
There are minimal requirements to be met. Making the PWA application installable, there is a need to modify your application entry point, add some minimal entries to Web App Manifest, allow search engines to crawl all your application pages, and configure your server properly.

Basic Entry Point:
The index.html must have some following entries in the <head> section:

  • mobile viewport configuration
  • Title tag
  • Description tag
  • Favicon tag
  • Link for apple-touch-icon tag
  • Link for mask-icon tag
  • Meta entry for theme-color tag
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>My title here</title>
    <meta name="description" content="My description here">
    <link rel="icon" href="/favicon.ico">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png" sizes="180x180">
    <link rel="mask-icon" href="/mask-icon.svg" color="#FFFFFF">
    <meta name="theme-color" content="#ffffff">
</head>
Enter fullscreen mode Exit fullscreen mode

WEB APP MANIFEST CONFIGURATION
There are some configurations we had to make in the vite-config.js file to make our Web App Manifest have a perfect result:

  • A scope: This can be omitted for simplicity. The vite-plugin-pwa plugin uses the Vite base option to configure it by using the default (“/ “). And this was omitted in my configuration.
  • Name: It is the name you want to give to your app.
  • Short_name: It is the short form of your name, like a nickname. Note: You must provide at least the short_name or name property. If both are provided, short_name is used on the user's home screen, launcher, or other places where space may be limited. name is used when the app is installed. ·
  • Description: It is the area to state the purpose of the app or a summary of the app.
  • Theme_color: The theme_color sets the color of the toolbar and also reflects in the app’s preview in task switchers which must match the configured one on the Entry Point theme-color at the header tag.
  • Background Color: The background_color is mostly the same color as the load page, to provide a smooth transition from the splash screen to the app.
  • Display: The display customize what browser UI is shown when the app is launched.
  • Icons: The Icons are the images that will display on your home screen in which you can define a set of icons for the browser to use on the home screen. Icons property is an array of image objects in which each object must include the src, a sizes property, and the type of image.

Note: You can use PWA manifest Generator to generate all your Icons and manifest configurations.

SEARCH ENGINES
To allow search engines to crawl all the application pages, you have to add robots.txt to the public folder on the application. The public folder must be on the root folder of the application, not inside the src folder.

Fig 1.2: Shows the robots.txt file in public folder.
robots.txt for search engines crawl.
Fig 1.3: Shows the content in robots.txt file.
search engine
Fig 1.4: Shows the complete manifest configuration in vite.config.js.
Manifest Configuration

Cleanup Outdated Caches
This will help delete the old cache and update it with a new one after changes. The service worker will store all application assets in a browser cache (or set of caches). Every time you make changes to your application and rebuild it, the service worker will also rebuild, including in its precache manifest all new modified assets, which will have their revision changed (all assets that have been modified will have a new version).
Since Workbox v4.0.0, a Boolean configuration option was introduced.
The option cleanupOutdatedCaches was added to the GenerateSw mode. If it is set to true, a call to workbox.precaching.cleanupOutdatedCaches() will automatically be added to the generated service worker, which will delete any out-of-date precaches which are no longer used by Workbox.
Any version lower than v4.0.0, have to configure to automatically update the new changes and delete the old precach.
For more details check Workbox Changelog site or Worbox-routing site

export default defineConfig({
  plugins: [
    VitePWA({
      workbox: {
        cleanupOutdatedCaches: false
      }
    })
  ]
})
Enter fullscreen mode Exit fullscreen mode

Fig 1.5: Shows the overall vitepwa configuration in vite.config.js.
PWA Configuration

Building Web Application:
At this point, we can now run npm run build to wrap all the web applications and configure all our service worker and web app manifest.

After the application had been built successfully, all the applications will be wrapped in the dist folder alongside sw.js file, registers.js file, manifest.webmanifest file which is a JSON file, workbox.js file. Also, all our applications CSS, Js, Html, will be rap up in different files inside the assets folder. While all fonts and icons still maintain their normal folder name.
Fig 1.6: Shows the output files after building the app in dist folder.
Result

WEB SERVER FOR CHROME
Web Server for Chrome is one of the environments I use to test my application on my localhost.

Step I: Search for Web Server Chrome extension page and click on Add to Chrome to add it to your chrome page if you don’t have it already.
Fig 1.7: Shows the Web Server for Chrome and where to click.
Web Server Chrome

Step II: Launch the Web Server from your list of Chrome Apps extension.
Fig 1.8: Shows the logo of Web Server in chrome apps.
Chrome Apps Extension

Step III: The web server will instantly start and a window will appear with a bunch of options. The first thing you’ll need to do is specify a web directory – the place where all of the Html and related files you want to use with your web server are stored. In our case all our files are inside the dist folder. To do so, click the CHOOSE FOLDER button.
Fig 1.9: Shows the choose folder button to be click on Web Server.
Web Server

Step IV: Navigate to the directory that contains the files that make up your website, select it and click the Select Folder button.
Fig 1.10: Shows the dist folder and select folder button click.
adefam

Step V: You can now view the website by visiting the URL http://localhost:8887 or http://127.0.0.1:8887. You can decide to change the setting or click on different options based on your choice.
Fig 1.11: Shows the URL link to be click.
adefam image

Step VI: The website will be open on the local host and you will be prompted to install it on your browser by clicking the install icons on the right side of the URL link bar.
Fig 1.12: Shows the Installation button on chrome browser.
PWA Installation

Step VII: Click on the Icons install on your home screen if you are on mobile or desktop area if you are using a system.
Fig 1.13: Shows the logo of Web app on desktop.
PWA Logo
At this point, you can confirm all your configuration if it is working perfectly.
By moving your mouse on the Icons, you will see that the Icon label with the name provided in the manifest configuration and also the description will pop up.
Fig 1.14: Shows the logo name and description.
PWA Logo Description

Let's Open the app, then you will observe the theme_color provided at the title bar alongside the name provided in the manifest and details provided at the title tag.
Fig 1.15: Shows the title and the color theme.
PWA theme_color

To check the progress of the service worker and monitor the performance, you can go ahead and inspect the web application on the browser and click on the application option.
Fig 1.17: Shows the application area on DevTools.
PWA Performance

To further learn about VUE PWA, also on how to inspect and apply push notifications, watch a Master PWA in Vue – JavaScript Marathon presented by Simone Cuomo, a Senior Software Engineer at This Dot Labs

References

Top comments (2)

Collapse
 
prodesquare profile image
Hamza Mughal

Hi there! Thanks for this wonderful article. Can you please tell me how to fix vite pwa plugin showing homepage on every route (that was meant to be 404)?

Collapse
 
adefam profile image
Famosa Adegbite

If the Vite PWA plugin is causing your homepage to be displayed on every route that was meant to be a 404, there might be an issue with your configuration or how you're using the plugin.

Try and troubleshoot the project:

First, Check Your Configuration: Ensure that your Vite PWA plugin configuration is set up correctly.

  1. Check Service Worker Scope: The issue might be related to the service worker's scope. Make sure the service worker's scope is set correctly in your configuration. If the scope is too broad, it could be causing the homepage to appear on every route.

  2. Cache and Cache Strategy: Verify the caching strategy you're using with the Vite PWA plugin. Make sure you're caching the appropriate assets and using the right cache strategy for your use case.

  3. Check Routes and Navigation: Ensure that your routes are defined correctly and your navigation is set up properly.

Lastly Testing in Incognito Mode: Sometimes, browser caching can cause unexpected behavior. Test your application in an incognito or private browsing mode to ensure that the issue is not related to cached data.

Any of the options can solve the problem. But if you are still facing challenges you can share more light with your code