我正在尝试使用 create-react-app 中的服务工作者,但我不断收到...不会注册 sw.当前环境:开发 [英] I'm trying to make use of the service worker in create-react-app but I keep getting...wont register sw. Current env: development

查看:43
本文介绍了我正在尝试使用 create-react-app 中的服务工作者,但我不断收到...不会注册 sw.当前环境:开发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 create-react-app 但 service worker 不工作.我使用本地主机

我正在尝试使其成为 PWA,我正在使用创建反应应用程序时生成的库存清单文件和服务工作者,我还 rand npm run-script 构建并获得了生成的服务工作者.js 文件.问题是我一直在控制台中得到这个.不会注册 sw.当前环境:开发帮助?

window.addEventListener("load", () => {const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;如果(isLocalhost){//这是在本地主机上运行的.让我们检查是否有 service worker仍然存在与否.checkValidServiceWorker(swUrl, config);//向本地主机添加一些额外的日志记录,将开发人员指向这//服务工作者/PWA 文档.navigator.serviceWorker.ready.then(() => {控制台.日志(此网络应用程序由服务缓存优先" +工人.要了解更多");});} 别的 {//不是本地主机.只需注册服务工作者registerValidSW(swUrl, config);}});} 别的 {console.log("不会注册 sw.当前环境:", process.env.NODE_ENV);}}

解决方案

步骤如下:

第 1 步:需要在 public 文件夹中创建一个新的 JavaScript 文件:svcWorker.js.在其中添加以下代码:

var CACHE_NAME = 'task-manager-pwa';var urlsToCache = ['/','/完全的'];//安装服务工作者self.addEventListener('安装', 事件 => {//执行安装步骤事件.等待直到(caches.open(CACHE_NAME).then(函数(缓存){console.log('缓存打开');返回 cache.addAll(urlsToCache);}));});//缓存并返回请求self.addEventListener('fetch', event => {event.respondWith(caches.match(event.request).then(功能(响应){//当缓存被命中时返回响应如果(响应){返回响应;}返回 fetch(event.request);}));});//更新服务工作者self.addEventListener('激活', 事件 => {var cacheWhitelist = ['task-manager-pwa'];事件.等待直到(caches.keys().then(cacheNames => {返回 Promise.all(cacheNames.map(cacheName => {if (cacheWhitelist.indexOf(cacheName) === -1) {返回 caches.delete(cacheName);}}));}));});

第 2 步:对 index.html 文件进行更改,以检查客户端浏览器是否支持 Service Worker,以及应用程序是否呈现样式并正常工作,而没有任何 JavaScript 加载痕迹.在 <style> 之间添加了用于此的代码.</style> 标签.这是 index.html 中的完整代码:

<html lang="zh-cn"><头><meta charset="utf-8"/><link rel="快捷图标" href="%PUBLIC_URL%/favicon.ico"/><元名称=视口"内容=宽度=设备宽度,初始比例= 1"/><meta name="theme-color" content="#000000"/><元名称=说明"content="使用 create-react-app 创建的网站"/><link rel="apple-touch-icon" href="logo512.png"/><link rel="manifest" href="%PUBLIC_URL%/manifest.json"/><title>React PWA 应用</title><style type="text/css">身体 {边距:0;填充:0;字体系列:无衬线;}.导航栏{背景色:#4169e1;}.navbar h3 {显示:内联块;文本对齐:左;填充:10px;颜色:黑色;文字装饰:无;}.navbar {显示:内联块;填充:10px;颜色:#fff;文字装饰:无;}.page-info {填充:10px;}.当前的 {颜色:#2e8b57;}.完全的 {颜色:#ff6347;文字装饰:行进;}</风格><身体><noscript>启用 JavaScript 以运行此应用程序.</noscript><div id="root"><div class="navbar"><h3>任务管理器</h3><a href="/">当前任务</a><a href="/completed">已完成的任务</a>

<p class="页面信息">应用加载中...</p>

<脚本>如果(导航器中的'serviceWorker'){window.addEventListener('load', function() {navigator.serviceWorker.register('svcWorker.js').then(function(registration) {console.log('worker 注册成功', registration.scope);}, 函数(错误){console.log('工人注册失败', err);}).catch(函数(错误){控制台日志(错误);});});} 别的 {console.log('您的浏览器不支持 Service Worker.');}</html>

第 3 步:在 index.js 中,确保使用:serviceWorker.register()下面是 index.js 中的代码:

从'react'导入React;从 'react-dom' 导入 ReactDOM;导入'./index.css';从'./App'导入应用程序;import * as serviceWorker from './serviceWorker';ReactDOM.render(, document.getElementById('root'));//如果你想让你的应用离线工作并加载得更快,你可以改变//unregister() 到 register() 下面.请注意,这会带来一些陷阱.serviceWorker.register();

我已经在我的博客文章中编写了所有这些步骤和其他步骤来创建一个简单的 React PWA 应用程序,并在 GitHub 中使用工作代码.请参考:http://softwaredevelopercentral.blogspot.com/2019/10/react-pwa-tutorial.html

I'm using create-react-app but the service worker isnt working. Im using localhost

I'm trying to make this a PWA, i'm using the stock manifest file and service worker generated when you create-react-app, i've also rand npm run-script build and got the generated service-worker.js file. The problem is that I keep getting this in the console. wont register sw. Current env: development help?

window.addEventListener("load", () => {
   const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

   if (isLocalhost) {
    // This is running on localhost. Let's check if a service worker 
       still exists or not.
        checkValidServiceWorker(swUrl, config);

    // Add some additional logging to localhost, pointing developers to 
      the
    // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            "This web app is being served cache-first by a service " +
              "worker. To learn more"
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  } else {
    console.log("wont register sw. Current env:", process.env.NODE_ENV);
  }
}

解决方案

Here are the steps:

Step 1: A new JavaScript file: svcWorker.js needs to be created in the public folder. Add the following code in it:

var CACHE_NAME = 'task-manager-pwa';
var urlsToCache = [
  '/',
  '/completed'
];

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

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

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

Step 2: Make changes to the index.html file to check if the client browser supports service workers and also the application renders styling and works fine without any trace of JavaScript loading. Code for this is added between the <style> </style> and <body> </body> tags. Here is the full code in index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1"
    />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="logo512.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React PWA App</title>
    <style type="text/css">
      body {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .navbar {
        background-color: #4169e1;
      }
      .navbar h3 {
        display: inline-block;
        text-align: left;
        padding: 10px;
        color: black;
        text-decoration: none;
      }
      .navbar a {
        display: inline-block;
        padding: 10px;
        color: #fff;
        text-decoration: none;
      }
      .page-info {
        padding: 10px;
      }
      .Current {
        color: #2e8b57;
      }
      .Completed {
        color: #ff6347;
        text-decoration: line-through;
      }
    </style>
  </head>
  <body>
    <noscript>Enable JavaScript to run this app.</noscript>
    <div id="root">
      <div class="navbar">
        <h3>Task Manager</h3>
        <a href="/">Present Tasks</a>
        <a href="/completed">Finished Tasks</a>
      </div>
      <p class="page-info">
        App Loading...
      </p>
    </div>
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('svcWorker.js').then(function(registration) {
            console.log('Worker registration is successful', registration.scope);
          }, function(err) {
            console.log('Worker registration has failed', err);
          }).catch(function(err) {
            console.log(err);
          });
        });
      } else {
        console.log('Service Worker is not supported by your browser.');
      }
    </script>
  </body>
</html>

Step 3: In index.js, make sure that you use: serviceWorker.register() Here is code in index.js:

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.
serviceWorker.register();

I have written all these steps and other steps to create a Simple React PWA App in my blog post with working code in GitHub. Please refer to: http://softwaredevelopercentral.blogspot.com/2019/10/react-pwa-tutorial.html

这篇关于我正在尝试使用 create-react-app 中的服务工作者,但我不断收到...不会注册 sw.当前环境:开发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆