Hugo PWA Setup
有些客戶想要自己的業務APP, 但只是想將公司手機版網站打包成APP, 這情況比起另外開發一個APP, 把網站加工成Progressive Web App (PWA)更省時費力, 然後騙客戶把APP做出來了(X
Step 1: 新增導入 PWA 的Script
layouts/partials/pwa.html
<meta name=”apple-mobile-web-app-capable” content=”yes”>
<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
// Use the window load event to keep the page load performant
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js');
});
}
</script>
然後在 layouts/_default/baseof.html 的header加入
{{ partial "pwa.html" }}
Step 2: 新增 Manifest
用線上 favicon generator基本會自動生成出來
static/manifest.json
{
"short_name": "Wagnaria",
"name": "Wagnaria",
"icons": [
{
"src": "\/favicon\/android-icon-36x36.png",
"sizes": "36x36",
"type": "image\/png",
"density": "0.75"
},
{
"src": "\/favicon\/android-icon-48x48.png",
"sizes": "48x48",
"type": "image\/png",
"density": "1.0"
},
{
"src": "\/favicon\/android-icon-72x72.png",
"sizes": "72x72",
"type": "image\/png",
"density": "1.5"
},
{
"src": "\/favicon\/android-icon-96x96.png",
"sizes": "96x96",
"type": "image\/png",
"density": "2.0"
},
{
"src": "\/favicon\/android-icon-144x144.png",
"sizes": "144x144",
"type": "image\/png",
"density": "3.0"
},
{
"src": "\/favicon\/android-icon-192x192.png",
"sizes": "192x192",
"type": "image\/png",
"density": "4.0"
},
{
"src": "\/favicon\/favicon-512x512.png",
"sizes": "512x512",
"type": "image\/png",
"density": "5.0"
}
],
"start_url": "/?source=pwa",
"background_color": "#001020",
"display": "standalone",
"theme_color": "#001020"
}
Step 3: 新增 Service Worker
static/service-worker.js
// https://developers.google.com/web/tools/workbox/guides/get-started
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');
if (workbox) {
console.log(`Yay! Workbox is loaded 🎉`);
workbox.routing.registerRoute(
new RegExp(/\/.*/),
workbox.strategies.networkFirst()
);
workbox.routing.registerRoute(
// Cache CSS files
/.*\.css/,
// Use cache but update in the background ASAP
workbox.strategies.staleWhileRevalidate({
// Use a custom cache name
cacheName: 'css-cache',
})
);
workbox.routing.registerRoute(
// Cache image files
/.*\.(?:png|jpg|jpeg|svg|gif)|https:\/\/www\.codewars\.com\/users\/AoiYamada\/badges\/micro/,
// Use the cache if it's available
workbox.strategies.cacheFirst({
// Use a custom cache name
cacheName: 'image-cache',
plugins: [
new workbox.expiration.Plugin({
// Cache only 20 images
maxEntries: 20,
// Cache for a maximum of a week
maxAgeSeconds: 7 * 24 * 60 * 60,
})
],
})
);
} else {
console.log(`Boo! Workbox didn't load 😬`);
}
完成
接下來用移動設備打開網站時, Android會詢問是否安裝到桌面, IOS需要手動在Safari按新增到桌面
上架支援方面目前還不是很完善, 粗略看了一下, Play Store上架需要外包一層JAVA APP, App Store暫時不支援
不過製作 PWA 形式的APP是網站開發的趨勢, 相信 PWA 很快就能在所有平台無痛上架