DEV Community

loading...
Cover image for Convert React App into a Progressive Web App (PWA)

Convert React App into a Progressive Web App (PWA)

phonerefer profile image Irshad Ali ・3 min read

PWA ReactJs

What is a PWA?

Progressive Web Apps are user experiences that have the reach of the web, and are:

Reliable - Load instantly and never show the downasaur, even in uncertain network conditions.
Fast - Respond quickly to user interactions with silky smooth animations and no janky scrolling.
Engaging - Feel like a natural app on the device, with an immersive user experience.

This new level of quality allows Progressive Web Apps to earn a place on the user's home screen.

1. Register a Service Worker

What is a service worker?
Service workers (client-side proxies that pre-cache key resources) enable PWAs to load instantly and provide an instant,
reliable experience for users, regardless of the network state.

Create a new worker.js file in the public folder (public/worker.js) and add the following code:

Let CACHE_NAME = 'your-app-name';
Let urlsToCache = [
  '/',
  '/completed'
];

// Install a service worker
self.addEventListener('install', event => {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

// Cache and return requests
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

// Update a service worker
self.addEventListener('activate', event => {
  Let cacheWhitelist = ['your-app-name'];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

Note! from above code replace (your-app-name) with your app name

2. Now Update HTML

Update your index.html file in the public folder (public/index.html)
to check if the client’s browser supports service workers. Just Add below code inside the body tag of your app's (public/index.html)

<script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('worker.js').then(function(registration) {
            console.log('Worker registration successful', registration.scope);
          }, function(err) {
            console.log('Worker registration failed', err);
          }).catch(function(err) {
            console.log(err);
          });
        });
      } else {
        console.log('Service Worker is not supported by browser.');
      }
    </script>

3. Activating ServiceWorker

Now go to your app's index.js in the src folder (src/index.js)

Now Update serviceWorker.unregister() to serviceWorker.register() Like Below Code At Last Line

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.register();

Restart (npm start) and reload your React app — you should see the message “Worker registration successful” in the console.

4. Create a manifest.json file

Manifest is a simple JSON file that tells the browser about your web application and how it should behave when 'installed' on the user's mobile device or desktop. Having a manifest is required by Chrome to show the Add to Home Screen prompt.

A typical manifest file includes information about the app name, icons it should use, the start_url it should start at when launched, and more.

{
    "name": "your-app-name",
    "short_name": "your-app-name",
    "icons": [
        {
            "src": "img/logo.png",
            "sizes": "92x92",
            "type": "image/png"
        },
        {
            "src": "/img/logo.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "img/logo.png",
            "sizes": "152x152",
            "type": "image/png"
        }        
    ],
    "start_url": "/",
    "display": "standalone",
    "orientation": "portrait",
    "background_color": "#f0f2f5",
    "theme_color": "#96f2d7"
}

That's it 🎉 Congratulations, you just created a working progressive web app!

Give A heart ❤️ To Appreciate My Work And Follow Me For More Awesome Content.

This Is "irshad ali"

Check Out React PWA Demo: https://www.irshadali.site

Discussion

pic
Editor guide
Collapse
emmytobs profile image
Emmytobs

Using create-react-app puts in a 'serviceWorker.js' file in the root of my app while the manifest lives in the public folder. I will like to know if calling 'serviceWorker.register()' in the index.js file will be enough to install, activate and cache the desired files.

I am asking this because, in the 'worker.js' file, I can't really know what files to cache. I do not have any static files that i can easily point to. Moreover, there will be a build folder where all my application code will be bundled and minified.

Please could you help further explain what you did when you added the '/' and '/completed' files in the worker.js file to cache. Thanks

Collapse
krystianwojtowicz profile image
krystianwojtowicz

after npm start i have :
[HMR] Waiting for update signal from WDS...
react-dom.development.js:25028 Download the React DevTools for a better development experience: fb.me/react-devtools
index.js:11 Uncaught ReferenceError: serviceWorker is not defined
at Module../src/index.js (index.js:11)
at webpack_require (bootstrap:785)
at fn (bootstrap:150)
at Object.1 (index.js:11)
at webpack_require (bootstrap:785)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback as push
at main.chunk.js:1
spa:17 Worker registration failed DOMException: Failed to register a ServiceWorker for scope ('localhost:3000/') with script ('localhost:3000/worker.js'): The script has an unsupported MIME type ('text/html').
index.js:1 ./src/index.js
Line 11:1: 'serviceWorker' is not defined no-undef

Search for the keywords to learn more about each error.
console. @ index.js:1

Collapse
phonerefer profile image
Irshad Ali Author

Do you have any Programming idea dude

Collapse
rukeeo1 profile image
Rukee Ojigbo

Thanks man