Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Jeff Posnick
Jeff Posnick

Posted on

     

Service workers in create-react-app v4+

Ever since built-in support for service workers was added tocreate-react-app v2, developers have been asking for more control over the resulting service worker's functionality. This might mean disablingprecaching in favor of solelyruntime caching, or it might mean adding inpush notification orweb share target support.

create-react-app v4+ willcheck for the presence of asrc/service-worker.js file at build time, and if found, runworkbox-webpack-plugin'sInjectManifest plugin, passing in that file as theswSrc parameter.

If you're starting a new project and follow the instruction fromcreate-react-app's "Making a Progressive Web App" guide, i.e. you runnpx create-react-app my-app --template cra-template-pwa, you'll end up with everything in the right place.

Which is to say your project will:

  • automaticallybundle the code insrc/service-worker.js (transforming the ES module imports into code that can be run inside the service worker)
  • look for the symbolself.__WB_MANIFEST somewhere inside yoursrc/service-worker.js, and replace it with aprecache manifest, consisting of URLs and revision info about all yourwebpack assets, so that Workbox can precache them.

If you're not interested in precaching yourwebpack assets, then you don't need to use theInjectManifest plugin at all, and you can just put whatever code you want in a file namedanything other thansrc/service-worker.js, and register that file as your service worker. That's up to you.

If you are interested in Workbox's precaching, but you're upgrading from an oldercreate-react-app and you don't have a "correct"src/service-worker.js file, you can manually copy thefile from the template into your project.

(This post was adapted from aStack Overflow response.)

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a member of Google's Web DevRel team, focusing on Progressive Web Apps.
  • Location
    Brooklyn, NY
  • Joined

More fromJeff Posnick

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp