DEV Community

loading...

Service workers in create-react-app v4+

jeffposnick profile image Jeff Posnick ・2 min read

Ever since built-in support for service workers was added to create-react-app v2, developers have been asking for more control over the resulting service worker's functionality. This might mean disabling precaching in favor of solely runtime caching, or it might mean adding in push notification or web share target support.

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.

If you're starting a new project and follow the instruction from create-react-app's "Making a Progressive Web App" guide, i.e. you run npx 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:

  • automatically bundle the code in src/service-worker.js (transforming the ES module imports into code that can be run inside the 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.

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. 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.

(This post was adapted from a Stack Overflow response.)

Discussion (0)

Forem Open with the Forem app