最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to add service-worker.js to existing react app, if yes, how? - Stack Overflow

programmeradmin7浏览0评论

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.

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.

Share Improve this question edited Nov 16, 2022 at 7:03 lunaayase asked Nov 16, 2022 at 7:00 lunaayaselunaayase 751 gold badge1 silver badge8 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

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.');
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论