Manually generating a Service Worker is ok, but at some point you’ll want to automate it as part of your build process, not having to worry about that anymore.
In this lesson you’ll see how to use sw-precache-webpack-plugin in order to integrate service worker’s generation in your webpack build.
Instructor: [00:00] It's more convenient to have the service worker generation as part of your build. Since we are using webpack, we can use the service worker precache webpack plugin.
[00:11] First, let's remove the SV config file, because we don't need it anymore, and then open a console and install sw-precache webpack plugin. Now let's open the webpack config file. Up here, let's import the sw-precache webpack plugin. Require sw-precache-webpack plugin. Then let's use it where you have your plugins defined.
[00:56] I have it down here, so have to write new service worker precache. [inaudible] are not set as a configuration. First thing we can configure is the cache ID, which is a string that will be prepended to the cache entry of your app. Let's call it my-awesome-app.
[01:25] By default, webpack will place the service worker in the same directory as your output.path, which in this case is this. We want to place it in the root directory, because the scope of the service worker depends on where it's placed.
[01:40] We can access that directory and subdirectories but not parent directories. That's not what we want, because we want to cache the index.html file as well. That wouldn't be possible if it's not in the same directory.
[01:55] You can write filepath and say serviceworker.js. Then it will be created with that name in that path. By default, the service worker precache plugin will cache the files that go through the webpack graph. The rest of the static files, like the index.html, that doesn't go through the graph.
[02:18] For that, we can write static file loops, and it has the same syntax as the SW config file as before. Here, we can define the index.html, then the manifest.json, and then everything with the [inaudible] CSS and JS into this folder.
[02:42] Finally, the plugin will also prefix the files that tries to find, like in this HTML manifest, with the same directory of your output.path, which in this case is this. It will try to find it as this/index.html, this/manifest.json.
[03:02] In order to avoid that, we have to use the [inaudible] prefix property and write [inaudible] . That's the route of your app. You run npm run build again, then the service worker is created right here as you can see.
[03:21] You can see also that here it's using the cache ID that we have defined, and that the paths are correct. We still haven't used the service worker because we have to register it, but we'll see that later. Depends on where it's placed.