给网站添加PWA

232 阅读2分钟

什么是 PWA

渐进式 Web 应用程序 (PWA) 使用现代 API 进行构建和增强,提供增强的功能、可靠性和可安装性,同时只需一个代码库就可以借助任何设备触及任何人、任何地方。

渐进式网络应用程序(progressive web application - PWA),是一种可以提供类似于 native app(原生应用程序) 体验的 web app(网络应用程序)。PWA 可以用来做很多事。其中最重要的是,在**离线(offline)**时应用程序能够继续运行功能。这是通过使用名为 Service Workers 的 web 技术来实现的。

workbox-webpack-plugin

Workbox 是 Google Chrome 团队推出的一套 PWA 的解决方案,这套解决方案当中包含了核心库和构建工具,因此我们可以利用 Workbox 实现 Service Worker 的快速开发。

添加 Workbox

pnpm i -D workbox-webpack-plugin

webpack 配置

const {GenerateSW} = require('workbox-webpack-plugin');

new GenerateSW({
  // importWorkboxFrom: 'local',
  cacheId: 'huxy-pwa',
  skipWaiting: true, // 跳过 waiting 状态
  clientsClaim: true, // 通知让新的 sw 立即在页面上取得控制权
  cleanupOutdatedCaches: true, // 删除过时、老版本的缓存
}),

注册 Service Worker

const initSW = () => {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker
        .register('./service-worker.js')
        .then(registration => {
          // console.log('SW registered: ',registration);
        })
        .catch(registrationError => {
          // console.log('SW registration failed: ',registrationError);
        });
    });
  }
};

manifest.json

引入 manifest.json

<link rel="manifest" href="/manifest.json">

manifest.json 配置

{
  "name": "pwa_test",
  "short_name": "test",
  "description": "pwa test",
  "lang": "cn",
  "display": "standalone",
  "orientation": "any",
  "start_url": ".",
  "theme_color": "#313131",
  "background_color": "#313131",
  "icons": [
    {
      "src": "./src/images/96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "./src/images/144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "./src/images/192.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "./src/images/512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

升级 nodejs 服务为 https

const https = require('https');
const fs = require('fs');
const path = require('path');

const ssl = path.resolve(__dirname, './ssl');
const options = {
  key: fs.readFileSync(`${ssl}/server.key`),
  cert: fs.readFileSync(`${ssl}/server.pem`),
};
const httpsServer = https.createServer(options, app);

本地创建测试证书

openssl req -nodes -new -x509 -keyout server.key -out server.cert

如果浏览器提醒 “您的连接不是私密连接” ,并禁止你访问。你可以直接在当前页面输入 thisisunsafe,不是在地址栏输入,而是直接敲击键盘输入,页面会自动刷新进入网页。

测试

huxy-admin 项目为例,测试一下效果。

可以通过 Chrome DevTools 里面的 Lighthouse 来检测,在 Categories 下勾选 Progressive Web App, 如果 PWA 选项没有点亮,则可根据提示进行修改。

也可以安装 lighthouse 包用命令行启动 Lighthouse :

lighthouse https://xxx.com --view

lighthouse.png