Missed the action at the 2018 Chrome Dev Summit? Catch up with our playlist on the Google Chrome Developers channel on YouTube. Watch now.

Generate a Service Worker with Webpack

This page explains how to use the workbox-webpack-plugin node module to generate a complete service worker with precaching and runtime caching.

Install `workbox-webpack-plugin`

Start by installing `workbox-webpack-plugin` from npm.

npm install workbox-webpack-plugin --save-dev

Setup your Webpack Config

To generate a service worker as part of your build process you'll need to add the plugin to your webpack.config.js file like so:

// Inside of webpack.config.js:
const WorkboxPlugin = require('workbox-webpack-plugin');

module.exports = {
  // Other webpack config...

  plugins: [
    // Other plugins...

    new WorkboxPlugin.GenerateSW()
  ]
};

The generated service worker will be setup to precache all the files in your webpack build.

In your web page, you can register this service worker by adding:

<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}
</script>

Adding Runtime Caching

There may be files that you don't want to precache but will be used by your webapp that you'd like cache at runtime. Images are a great example.

Instead of precaching all images for your site, which will take up a lot of space in the cache, you can cache them as they are used and limit the number of images cached.

Runtime caching can be achieved by adding the runtimeCaching configuration to the options passed into GenerateSW(). runtimeCaching expects an array of objects that describe the runtime caching rules you want.

In the example below, we'll demonstrate how to cache images and limit that cache to a maximum of 10 images.

// Inside of webpack.config.js:
const WorkboxPlugin = require('workbox-webpack-plugin');

module.exports = {
  // Other webpack config...

  plugins: [
    // Other plugins...

    new WorkboxPlugin.GenerateSW({
      // Exclude images from the precache
      exclude: [/\.(?:png|jpg|jpeg|svg)$/],

      // Define runtime caching rules.
      runtimeCaching: [{
        // Match any request ends with .png, .jpg, .jpeg or .svg.
        urlPattern: /\.(?:png|jpg|jpeg|svg)$/,

        // Apply a cache-first strategy.
        handler: 'cacheFirst',

        options: {
          // Use a custom cache name.
          cacheName: 'images',

          // Only cache 10 images.
          expiration: {
            maxEntries: 10,
          },
        },
      }],
    })
  ]
};

The full set of available options can be found on the Workbox Webpack module page.