Chrome Dev Summit 2018 is happening now and streaming live on YouTube. Watch now.

Precache Files with Workbox CLI

This page explains how to use the Workbox Command Line Interface (a.k.a the Workbox CLI) to generate the list of files to precache and add it to your service worker.

Install the CLI

To start, install the CLI from npm.

npm install workbox-cli --global

You should be able to run the command `workbox --help` after it's installed.

workbox --help

    workbox-cli is the command line interface for Workbox.

    Usage:
    $ workbox  [options]

    ...

Run the Wizard

The next step is to run the wizard. This will setup the CLi to work for your project. The wizard will ask a set of questions about your projects file structure which'll be used to determine the files that should be precached.

Start the wizard like so:

workbox wizard --injectManifest

Add an Injection Point

Before the files can be "injected" into your service worker, you need to add this line of code to your service worker file:

workbox.precaching.precacheAndRoute([]);

This piece of code will be replaced by the CLI with the list of files (See the next section).

Inject a Manifest with the CLI

The final step is to run the inject manifest command:

workbox injectManifest

This command will create the list of files to precache, read your service worker file, inject the manifest and output a new service worker file with the manifest. The end result with look like this:

workbox.precaching.precacheAndRoute([
  {
    "url": "basic.html",
    "revision": "7ca37fd5b27f91cd07a2fc68f20787c3"
  },
  {
    "url": "favicon.ico",
    "revision": "1378625ad714e74eebcfa67bb2f61d81"
  },
  {
    "url": "images/hamburger.svg",
    "revision": "d2cb0dda3e8313b990e8dcf5e25d2d0f"
  },

  ...

]);

When you make a change to your project, run the inject manifest command and you'll have an up to date service worker with precache support.

Further Reading

The workbox.precaching API provides some options for configuration should you need to customize any of the default behaviors. Learn more on the workbox.precaching page.