Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify auto generated service-worker in Create-React-App

I have created a sample app from Create-React-App library. When I ran the build command then it generates a service-worker on its own using cache-first strategy. But I need some more functionality like cache some API responses n all. I don't know how to modify the script which includes my own code in auto generated service-worker. I have found some help lines for my case but these are not enough to get a whole understanding of it.

By default, the generated service worker file will not intercept or cache any cross-origin traffic, like HTTP API requests, images, or embeds loaded from a different domain. If you would like to use a runtime caching strategy for those requests, you can eject and then configure the runtimeCaching option in the SWPrecacheWebpackPlugin section of webpack.config.prod.js.

Above paragraph is from official doc

Thanks in advance!

like image 772
Yash Kochar Avatar asked Sep 04 '17 13:09

Yash Kochar


People also ask

What is registerServiceWorker in react?

Register Service worker in create react app. registerServiceWorker.js. // In production, we register a service worker to serve assets from local cache. // This lets the app load faster on subsequent visits in production, and gives. // it offline capabilities.

How do I update an existing reacting project?

To update your React version, install the latest versions of the react and react-dom packages by running npm install react@latest react-dom@latest . If you use create-react-app , also update the version of react-scripts . Copied! The command will update the versions of the react-related packages.


2 Answers

We had a similar problem while working on a project recently and we didn't want to "eject". We created a little tool that allows you to append custom service worker code to the one generated by CRA.

Have a look here: https://github.com/bbhlondon/cra-append-sw

like image 139
tszarzynski Avatar answered Sep 22 '22 05:09

tszarzynski


You would can run npm run eject and get access to the underlying Webpack configuration.

Once you do that, the webpack.config.prod.js file can be modified to adjust your generated service worker. Look for the section that configures SWPrecacheWebpackPlugin.

You can add in an additional runtimeCaching configuration option to that section to accommodate your runtime caching needs.

like image 28
Jeff Posnick Avatar answered Sep 21 '22 05:09

Jeff Posnick