workbox-swでservice-workerを生成する

Task

2019年11月19日 18:35

1 年前に PWA について熱心に調べていましたが、やっと活躍の機会が現れたので、workbox-sw を使った Service Worker の生成を行います。

以前self.addEventListener('install', callback)といった生 Service Worker を Workbox を使った方式に書き換える記事を投稿しましたが、ある程度楽になったとはいえ Workbox の中身を書く必要がありました。

生 Service Worker から Workbox に乗り換える │hoge

今回は webpack(laravel-mix) を使った環境なので、workbox-sw を使って service-worker.js の生成をします。

Generate a Complete Service Worker | Workbox | Google Developers

yarn add -D workbox-sw workbox-webpack-plugin
const { GenerateSW } = require("workbox-webpack-plugin");

mix.webpackConfig({
  plugins: [
    new GenerateSW({
      clientsClaim: true,
      skipWaiting: true,
      runtimeChaching: [
        {
          urlPattern: new RegExp("/")。
          handler: "StateWhileRevalidate"
        }
      ]
    })
  ]
});

GenarateSWを webpack の plugin として追加することで、webpack でビルドを行う際に service-worker.js として生成されるようになる。

どのディレクトリに生成するか、名前はどうするかなどは option によって変更できる。

Workbox Build | Google Developers

laravel-mix ではデフォルトで public 直下に以下のコードが生成される。

/**
 * Welcome to your Workbox-powered service worker!
 *
 * You'll need to register this file in your web app and you should
 * disable HTTP caching for this file too.
 * See https://goo.gl/nhQhGp
 *
 * The rest of the code is auto-generated. Please don't update this file
 * directly; instead, make changes to your Workbox build configuration
 * and re-run your build process.
 * See https://goo.gl/2aRDsh
 */

importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);

importScripts("/precache-manifest.e45533044388a4afdf3d6e0f2971cf4b.js");

self.addEventListener("message", event => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 * See https://goo.gl/S9QRab
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
p { margin-bottom: 1em; } blockquote p { margin-bottom: initial; } #content ul { padding-left: 40px; } .token.operator { background-color: initial; }

関連記事