LoginSignup
13
15

More than 5 years have passed since last update.

vue-pwa-plugin で Service Worker をカスタマイズする

Last updated at Posted at 2018-08-19

はじめに

vue-cliにはPWAのプラグインがあってデフォルトでキャッシュなどの処理を行ってくれるServiceWorkerを作成するようになっています。しかし、WebPushなどの別の機能も利用したい、というときがありますよね。そうしたときに、ServiceWorkerをカスタマイズする方法を紹介します。

Vue.jsやvue-cli自体について詳しく知りたい方は、こちらの記事をおすすめします。
- Vue.js を vue-cli を使ってシンプルにはじめてみる

環境

vue: 2.5.16
vue/cli: 3.0.1
vue/cli-plugin-pwa: 3.0.1

インストール

プロジェクトを作成したい場所で以下のコマンドを実行します。

$ npm install -g vue-cli
$ vue create my-project
? Please pick a preset:
> Manually select features
? Check the features needed for your project:
 (*) Babel
 (*) Progressive Web App (PWA) Support
 (*) Router
 (他にも好きなのを選んでください)
$ cd my-project
$ npm run build

設定の変更

ここでは、WorkboxのInjectManifestモードを使います。InjectManifestモードについて詳しくはドキュメントをどうぞ。

まずは、プロジェクトのルートディレクトリにvue.config.jsがなければ作成して、次のようにpwaのオプションを追加してください。

vue.config.js
module.exports = {
  pwa: {
    // configure the workbox plugin
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: 'src/service-worker.js',
      swDest: 'service-worker.js'

      // other options here...
    }
  }
}

次に、src/service-worker.jsを作成します。
そして、dist/service-worker.jsの内容を、冒頭に書いてあるimportScripts文を除いて、コピペします。

src/service-worker.jsは次のようになると思います。

src/service-worker.js
/**
 * 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
 */

workbox.core.setCacheNameDetails({prefix: "my-project"});

/**
 * 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.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

この部分ですが、Workboxのキャッシュを処理する部分になっています。ここを変更することでキャッシュの処理を変更することもできます。

また、このsrc/service-worker.jsですが、この後の部分に独自の内容を追記できます。(たとえばWebPushの処理など)

src/service-worker.jsに変更を加えて、もう一度npm run buildすると、dist/service-worker.jsに独自の内容を含んだServiceWorkerが作成されていることが確認できると思います。

関連リンク

https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#configuration
https://github.com/vuejs/vue-cli/issues/1481

13
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15