繁体   English   中英

是否可以将 service-worker.js 添加到现有的 React 应用程序中,如果可以,如何添加?

[英]Is it possible to add service-worker.js to existing react app, if yes, how?

使用 reactjs 学习 Progressive Web App,我知道要创建一个的应用程序,有一种不错的方法可以使用以下方法来创建一个新的应用程序:

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

然后,我通读了 crate-react-app 的文档,我知道 service-worker.js 是由于增加调试难度而选择加入的……但在这一点上,我想知道是否有任何方法可以添加服务-worker.js 之后/到不包含它的现有反应应用程序。

我也很好奇我是否可以创建一个新应用程序,获取该 service-worker.js 文件,然后插入任何其他 React 应用程序。 另外,这种方式是否需要进一步配置?

谢谢。

如果现有应用程序已由 create-react-app 创建,您只需在 index.js 旁边添加 service-worker.js 文件,因为 cra(create-react-app) 默认搜索 service-worker.js 以将其添加到构建目录在 index.js 中,您可以通过以下方式注册您的服务人员:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM