Home > Mobile >  Is it possible to add service-worker.js to existing react app, if yes, how?
Is it possible to add service-worker.js to existing react app, if yes, how?

Time:11-16

Studying Progressive Web App using reactjs and I know that to create a new app there is a decent way to do that for making a new app using the below:

npx create-react-app my-app --template cra-template-pwa

Then, I read through the docs of crate-react-app and I know service-worker.js is opt-in due to adding difficulties to debuug...but at this point, I am wondering are there any ways to add the service-worker.js afterwards/to existing react app that do not contain it.

I am also curious whether I could create a new app, grab that service-worker.js file and then plug to any other react apps. In addition, is there any further configuration is needed in this way?

Thanks.

CodePudding user response:

if existing app has been create by create-react-app you can simply add service-worker.js file beside index.js because cra(create-react-app) by default searching for service-worker.js to add that to build directory and in index.js you can register your service-worker in this way :

if ('serviceWorker' in navigator) {
  // Register a service worker hosted at the root of the
  // site using the default scope.
  navigator.serviceWorker.register(`${process.env.PUBLIC_URL}/service-worker.js`).then(
    registration => {
      console.log('Service worker registration succeeded:', registration);
    },
    /*catch*/ error => {
      console.error(`Service worker registration failed: ${error}`);
    }
  );
} else {
  console.error('Service workers are not supported.');
}
  • Related