Add more service-worker functionality with create-react-app

吃可爱长大的小学妹 提交于 2019-12-04 02:26:36

As you've observed, create-react-app's config is locked down, and the service worker logic is entirely defined in the config.

If you'd rather not eject but you want some customization, another option is to modify the create-react-app build process to explicitly call the sw-precache CLI after the normal build has completed, overwriting the service-worker.js that create-react-app generates by default. Because this involves modifying your local package.json, it doesn't require ejecting first.

There's some info on this approach here, and the general idea is modifying your npm scripts to look something like:

"build": "react-scripts build && sw-precache --config=sw-precache-config.js"

With sw-precache-config.js configured based on your needs, but including

swFilePath: './build/service-worker.js'

to ensure that the built-in service-worker.js is overwritten.

I had the same problem and without doing eject, I could replace the default service-worker with workbox-generated one to add runtime caching webfonts, api calls, etc.

  1. install workbox-build
  2. prepare src/sw-template.js to add your registerRoute calls
  3. prepare /build-sw.js to copy workbox file to 'build' folder and injectManifest
  4. modify package.json scripts to run above build-sw.js
  5. modify src/registerServiceWorker.js to replace the default one

You can find detailed file changes here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!