Published by @SoNiceInfo at 4/5/2020
Next.jsで作ったWebサイトをPWA(Progressive Web Apps)対応します。
PWA対応するとユーザがインストールすればそのサイトはインターネット環境がなくてもみれようになります。next-offlineというモジュールを使うと簡単に実装することができます。
manifest.jsonを用意するnext-offlineでServiceWorkerを用意するmanifest.jsonを用意するWebサイトのPWAの要件をまとめたmanifest.jsonを用意します。manifest.jsonの中では、名前、テーマカラー、アイコンなどを指定してPWAアプリを構成します。
例えば「SwiftUIへの道 - d1v1b」ではこのようになっています。start_urlではGoogle Analyticsの解析用にutm_source=pwaをつけています。
{
"name": "SwiftUIへの道",
"short_name": "Road2SwiftUI",
"start_url": "/swiftui?utm_source=pwa",
"display": "standalone",
"background_color": "#fff",
"theme_color": "#39f",
"description": "SwiftUIへの道ではSwiftUIを使って実現できることをコードと画像で紹介しています。",
"icons": [
{
"src": "https://d1v1b.com/images/icons/48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "https://d1v1b.com/images/icons/96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "https://d1v1b.com/images/icons/192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://d1v1b.com/images/icons/512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}next-offlineでServiceWorkerを用意するNext.jsでPWA対応するときはnext-offlineを使うとServiceWorkerを簡単に用意できます。
next-offlineをプロジェクトに追加しますnext.config.jsでServiceWorkerを準備するyarn add next-offlineconst withOffline = require('next-offline');
const nextConfig = {
target: 'serverless',
transformManifest: manifest => ['/'].concat(manifest),
// add the homepage to the cache
// Trying to set NODE_ENV=production when running yarn dev causes a build-time error so we
// turn on the SW in dev mode so that we can actually test it
generateInDevMode: true,
workboxOpts: {
swDest: 'static/service-worker.js',
runtimeCaching: [
{
urlPattern: /^https?.*/,
handler: 'NetworkFirst',
options: {
cacheName: 'https-calls',
networkTimeoutSeconds: 15,
expiration: {
maxEntries: 150,
maxAgeSeconds: 7 * 24 * 60 * 60, // 1 week
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
}
};
module.exports = withOffline(nextConfig);LighthouseはWebアプリの品質をGoogle目線で検査してくれるツールです。Lighthouseを使うにはChrome拡張機能をインストールします。
Lighthouse - Chrome ウェブストア
PWA対応したいサイトを開いてLighthouseでPWA対応状況を検査します。
以下のようにすべてグリーンでPassしていればPWA対応完了です。
対応できていなければ詳細をチェックしてガイドにしたがって修正しましょう。
