How can we use a Service Worker in our app?

So, how do we use a Service Worker in our application? Well, it's simple to do with Create React App, but there is a major caveat: you can't configure the Create React App default generated service-worker.js file without ejecting your project, unfortunately! Not all is lost, however; you can still take advantage of some of the highlights of PWAs and service workers by using the default Create React App-generated Service Worker.

To enable this, hop over into src/index.js, and, at the final line, change the Service Worker unregister() call to register() instead:

serviceWorker.register();

And now we're opting in to our Service Worker! Next, to actually see the results, you'll need to run the following:

$ yarn build

We'll create a Production build (We'll cover this in greater detail in Chapter 8Getting Your App Ready for Production). You'll see some output that we'll want to follow as part of this:

The build folder is ready to be deployed.
You may serve it with a static server:

yarn global add serve
serve -s build

As per the instructions, we'll install serve globally, and run the command as instructed. When we run this, we should see the following output:

$ serve -s build

We will get the following output:

Now open up http://localhost:5000 in your local browser and you'll be able to see, again in the Chrome Developer tools, the Service Worker up and running for your application:

Note that the rule of requiring HTTPS for Service Workers and PWAs is not in effect when you're running it on localhost!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.169.94