PWA in VUE VITE
Tags: webdev, vue, pwa, vite
Published: 2022-11-21 17:03:56

**HOW I MAKE [MY PORTFOLIO](http://adegbitefamosa.com.ng) 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](https://web.dev/learn/pwa/) 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](https://web.dev/add-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](https://web.dev/add-manifest/), 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**
```javascript
npm i vite-plugin-pwa -D
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bun7aj5g36b11o8ttsb.PNG)

**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`.
```javascript
import { VitePWA } from 'vite-plugin-pwa'
```
_Secondly:_ put it to use in the config under plugins:
```javascript
export default defineConfig({
    plugins: [
       VitePWA({
          registerType: 'autoUpdate'
        })
    ]
})
```
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.
```javascript
export default defineConfig({
   plugins: [
      VitePWA({
         injectRegister: 'auto'
      })
   ]
})
```
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.
```javascript
<head>
  <script>
    if('serviceWorker' in navigator) {
       window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js', { scope: '/' })
      })
    }
  </script>
</head>
```

2. **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:
```javascript
<head>
    <script src="/registerSW.js"></script>    
</head>
```
The `registers.js` file will contain normal service worker script.
```javascript
if('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js', { scope: '/' })
    })
}
```
3. **Null Method:** `injectRegister: null` This method will do nothing but allow you to register the service worker manually.
6. **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.
```javascript
workbox: {
   globPatterns: ['**/*.{js,css,html,ico,png,svg,json,vue,txt,woff2}']
},
```

**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
```javascript
<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>
```

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjmlnmtji09xmne5zlbc.PNG).
**Fig 1.3:** Shows the content in `robots.txt` file.
![search engine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ovvscq5kgy1w8w9c3o8.PNG)
**Fig 1.4:** Shows the complete manifest configuration in `vite.config.js`.
![Manifest Configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtwo8moozm4qjxbgkxhi.PNG)

**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](https://changecast-3.vercel.app/) or [Worbox-routing site](https://newreleases.io/project/npm/workbox-routing/release/4.0.0-beta.2)
```javascript
export default defineConfig({
  plugins: [
    VitePWA({
      workbox: {
        cleanupOutdatedCaches: false
      }
    })
  ]
})
```
**Fig 1.5:** Shows the overall vitepwa configuration in `vite.config.js`.
![PWA Configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x16o5bxqcpp84p9pbl70.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6zaeyswx68d0rn4pyxq.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4q4bx1ablanknw8ko2o.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nlkq90bvj7els8hhv9c.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/83d7z67rw9g9lzt48xha.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tarza881lad51mxhulqo.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3cgkwkj3gxs60asr5kq.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dqtr1bcaqu71tny1usm.PNG)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/msxv8x1mjncxyhcv7e9p.PNG)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8ebast5zm6v3wl5t3km.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g9oi5nl7rcz3r2c33ej3.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bvea6opbelzmfy022dy.PNG)

To further learn about VUE PWA, also on how to inspect and apply push notifications, watch a [Master PWA in Vue](https://www.youtube.com/watch?v=15Yr-J4X34M) – JavaScript Marathon presented by [Simone Cuomo](https://www.thisdot.co/author/simone-cuomo), a Senior Software Engineer at This Dot Labs

**References**
- [My Portfolio](http://adegbitefamosa.com.ng)
- [Learn PWA](https://web.dev/learn/pwa/)
- [Add a web app manifest](https://web.dev/add-manifest/)
- [Progressive web app](https://en.wikipedia.org/wiki/Progressive_web_app)
- [How to Run a Basic Web Server With Google Chrome July 9, 2021 / By Ross McKillop](https://www.simplehelp.net/2021/07/09/how-to-run-a-basic-web-server-with-google-chrome/)