備忘録

備忘録

Laravel MixでWorkboxを利用してオフライン利用可能にする方法

Ⅰ. はじめに

タイトルの通り「Laravel MixでWorkboxを利用してオフライン利用可能にする方法」です。
※この記事では触れませんが manifest.json を追加で作成するとPWA化できます。

Ⅱ. やり方

1. パッケージをインストールする
npm i -D workbox-sw
npm i -D workbox-webpack-plugin
2. ファイルを編集する

welcome.blade.php

...
<script>
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
  })
}
</script>
...

webpack.mix.js

const
  mix = require('laravel-mix'),
  workboxPlugin = require('workbox-webpack-plugin');

mix.webpackConfig({
  plugins: [
    new workboxPlugin.GenerateSW({
      swDest: 'service-worker.js',
      clientsClaim: true,
      skipWaiting: true,
      runtimeCaching: [
        {
          urlPattern: new RegExp('/#?/?$'), // 「/」と「/#/」をキャッシュする
          // urlPattern: new RegExp('/'), // 全てキャッシュする
          handler: 'StaleWhileRevalidate',
          options: {
            cacheName: 'index',
            expiration: {
              maxEntries: 1,
              maxAgeSeconds: 24 * 60 * 60 // 24時間
            },
            cacheableResponse: { statuses: [0, 200] }
          }
        }
      ]
    })
  ],
  output: {
    publicPath: ''
  }
});

mix
  .js('resources/js/app.js', 'public/js')
  .sass('resources/sass/app.scss', 'public/css');

実行結果

オフライン状態(①)でもServiceWorkerでキャッシュしている為(②)Webサイトを表示できている。
f:id:kagasu:20190528015326p:plain