0
0

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 1 year has passed since last update.

NextJS で作成したアプリを PWA化する

Last updated at Posted at 2022-10-16

目的

NextJS で作成したアプリを PWA 化するときの手順をメモ。

手順

1. manifest.json を作成

{
  "name": "App Name",
  "short_name": "App Name",
  "icons": [
    {
      "src": "./logo-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "./logo-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "theme_color": "#ffffff",
  "background_color": "#004740",
  "display": "standalone",
  "orientation": "portrait",
  "scope": "/",
  "start_url": "/"
}

icons は最低でも192px と 512px の2つが必要。

For Chromium, you must provide at least a 192x192 pixel icon, and a 512x512 pixel icon.

引用元: https://web.dev/add-manifest/#icons

display は、standalone を指定する事で、Native アプリのように、アドレスバーを非表示にしたり、通常のブラウザとは別でアプリを表示できるようになる。

orientation は、"portrait" を指定する事で画面を縦向きに固定できる。
その他のオプションは、「Nuxt.js(SPA)のWebサービスにmanifest.jsonを置くだけでホームに追加できるようになった」という記事で分かりやすく解説してくれています。

2.必要なファイルを読み込む

_document.js もしくは、_app.js で、manifest.jsonなどを読み込む。

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link rel="manifest" href="/manifest.json" />
          <link rel="apple-touch-icon" href="/icon.png"></link>
          <meta name="apple-mobile-web-app-capable" content="yes"/>
      <meta name="mobile-web-app-capable" content="yes" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

3.next-pwa をインストール

$ npm install next-pwa --save

4. next.config.json を設定

next.config.json を以下のように設定。

const withPWA = require('next-pwa')({
  dest: 'public'
})

module.exports = withPWA({
  // next.js config
})

で、npm run build をすると、public/ ディレクトリ内に、sw.jsworkbox-***.js が生成される。これが servicework 用のファイル。自動で読み込まれる。

このファイルはビルド時に毎回生成されるので、.gitignore に以下のように追記しておく

**/public/sw.js
**/public/workbox-*.js
**/public/worker-*.js
**/public/sw.js.map
**/public/workbox-*.js.map
**/public/worker-*.js.map

備考

  • apple-touch-icon の背景が透明だと、クリックして拡大表示までの背景が透明になり(デフォルトはbackground-color が適用?)不自然なので、アイコン側で色をつける事

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?