简体   繁体   English

如何将工作箱添加到 React 更新后

[英]How to add workbox to React post update

I have decided to try to use workbox but all of the guides i have seen talk about integrating with the service worker that react makes.我决定尝试使用 Workbox,但我看到的所有指南都在谈论与 react 制作的 service worker 集成。

But when i install a CRA i no longer get the service worker made for me.但是当我安装 CRA 时,我不再得到为我制作的服务人员。 What do i need to do to integrate workbox here?我需要做什么才能在此处集成工作箱?

This is my current code:这是我当前的代码:

App.js应用程序.js


    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import swDev from './swDev'
     
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    
    swDev()

swDev.js swDev.js


    export default function swDev(){
      let swURL = `${process.env.PUBLIC_URL}/sw.js`;
      if('serviceWorker' in navigator){
        navigator.serviceWorker.register(swURL).then(res => {
          console.log('Service worker has been registered');
        }).catch(err => console.log('Service worker was not registered'))
      }
    }

then this is the service worker in the public file那么这是公共文件中的服务人员

const cacheVersion = 'v1'


self.addEventListener('install', ()=>{
  console.log('Service worker has been installed');
})

self.addEventListener('activate', ()=>{
  console.log('Service worker is being activated');


})

self.addEventListener('fetch',(e)=>{

  e.respondWith(handleRequest(e.request))

  // function to update the cache
  // updateCache(e.request)

})


async function handleRequest(req){
  const cache = await caches.open(cacheVersion)
  const cacheRes = await cache.match(req)
  if(cacheRes){
    return cacheRes;
  }else{
    const netRes = await fetch(req);
    console.log(netRes);

    if(netRes.ok){
      return netRes;
    }else{
      // return an error message or something by matching it to a 404 page
      return netRes;
    }
  }
}

async function updateCache(req){

  if(navigator.onLine){
    const res = await fetch(req);
    const cache = await caches.open(cacheVersion);

    if(res.ok){
      // add the response to the caches and return the response
      await cache.put(req, res.clone())
    }

  }
}


create-react-app v4 will check for the presence of a src/service-worker.js file at build time, and if found, run workbox-webpack-plugin 's InjectManifest plugin , passing in that file as the swSrc parameter. create-react-app v4 将在构建时检查src/service-worker.js文件是否存在,如果找到,则运行workbox-webpack-pluginInjectManifest插件,将该文件作为swSrc参数传递。

If you're starting a new project and follow the instruction from create-react-app 's "Making a Progressive Web App " guide, ie you run npx create-react-app my-app --template cra-template-pwa , you'll end up with everything in the right place.如果您正在开始一个新项目并按照create-react-app的“制作渐进式 Web 应用程序”指南中的说明进行操作,即运行npx create-react-app my-app --template cra-template-pwa ,你最终会在正确的地方得到一切。

Which is to say your project will:也就是说,您的项目将:

  • automatically bundle the code in src/service-worker.js (transforming the ES module imports into code that can be run inside the service worker)自动捆绑src/service-worker.js中的代码(将 ES 模块导入转换为可以在 service worker 内部运行的代码)
  • look for the symbol self.__WB_MANIFEST somewhere inside your src/service-worker.js , and replace it with a precache manifest , consisting of URLs and revision info about all your webpack assets, so that Workbox can precache them.src/service-worker.js中的某处查找符号self.__WB_MANIFEST ,并将其替换为预缓存清单,其中包含有关所有webpack资产的 URL 和修订信息,以便 Workbox 可以预缓存它们。

If you're not interested in precaching your webpack assets, then you don't need to use the InjectManifest plugin at all, and you can just put whatever code you want in a file named anything other than src/service-worker.js , and register that file as your service worker.如果您对预缓存webpack资产不感兴趣,那么您根本不需要使用InjectManifest插件,您可以将您想要的任何代码放在一个名为src/service-worker.js之外的任何文件中,并将该文件注册为您的服务人员。 That's up to you.这取决于你。

If you are interested in Workbox's precaching, but you're upgrading from an older create-react-app and you don't have a "correct" src/service-worker.js file, you can manually copy the file from the template into your project.如果您对 Workbox 的预缓存感兴趣,但您是从较旧的create-react-app升级并且没有“正确”的src/service-worker.js文件,则可以手动将模板中的文件复制到你的项目。

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

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