2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

webpackでPWA化をするための設定

Last updated at Posted at 2020-02-24

どうもこんにちは、ウマシバ(@UMASHIBA)といいます。
今回、こちらのウェブアプリをwebpackを使ってPWA化しようとした際に結構詰まったので備忘録を兼ねて記事にします。

概要

今回、webpackでウェブアプリをPWA化するために使った主なwebpackライブラリは以下のようなものです。

PWAを作成するのに必要なservice-worker.jsmanifest.jsonをこれらを使って作成しました。

今回は、workbox-sw,workbox-webpack-pluginでservice-worker.jsを作成し、webpack-pwa-manifestでmanifest.jsonを作成した形です。

Workbox

WorkboxはGoogleが作成したservice-workerを作成するためのツールです。

workbox-swでworkboxの機能を使えるようにして、workbox-webpack-pluginでwebpackに対応させます。

webpack.config.jsに書いたコードは以下のようになりました。

const workBoxWebpackPlugin = require("workbox-webpack-plugin");
const outputPath = path.resolve(__dirname, "public");

module.export  ={
  ...
  ...
  plugins: [
    new workBoxWebpackPlugin.GenerateSW({
      swDest: outputPath + "/service-worker.js"
    })
  ]
}

swDestでservice-worker.jsの出力先を指定しています。

Webpack PWA Manifest

webpack-pwa-manifestはmanifest.jsonを生成するためのライブラリです。

webpack.config.jsに書いたコードは以下のようになりました。

const workBoxWebpackPlugin = require("workbox-webpack-plugin");
const outputPath = path.resolve(__dirname, "public");

module.export  ={
  ...
  ...
  plugins: [
    new WebpackPwaManifest({
      short_name: "3D Timer",
      name: "3D Ramen Timer",
      display: "standalone",
      start_url: "index.html",
      background_color: "#202124",
      theme_color: "#FF0000",
      icons: [{
        src: path.resolve("src/images/icon_512.png"),
        sizes: [96, 128, 192, 256, 384, 512],
      }]
    }),
    new workBoxWebpackPlugin.GenerateSW({
      swDest: outputPath + "/service-worker.js"
    })
  ]
}

もともとmanifest.jsonに書いていたものをwebpack.config.jsに書くことで出力先ディレクトリにmanifest.jsonが出力されます。

違う点はtheme-colorがtheme_colorになる点とiconsの指定方法です。

theme-colorに関してはmanifest.jsonに記載されず、出力先のindex.htmlにて以下のようなタグとして追加されます。
<meta name="theme-color" content="#FF0000" />

iconsに関しては
srcで指定したファイルからsizesで指定した大きさのファイルを作成してくれます。


以上がwebpackでPWA化するための設定です。
間違いに気づいた場合やより良い方法を知っているという方がいらっしゃいましたらコメントにてよろしくお願いします。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?