PWA

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

下面将使用 Workbox 构建一个离线应用程序.

1. 使用http-server包,workbox-webpack-plugin插件

npm install http-server --save-dev
npm install workbox-webpack-plugin --save-dev

2. webpack.common.js

// PWA
+    const WorkBoxPlugin = require('workbox-webpack-plugin');

plugins:[
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: 'PWA'
        }),
        new webpack.ProvidePlugin({
            join: ['lodash','join']
        }),
+        new WorkBoxPlugin.GenerateSW({
+            clientsClaim: true,
+            skipWaiting: true
        })
    ]

npm run build

 3. 注册service-worker

// index.js
 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);
        });
    });
}
// 构建
npm run build
// 启动http-server
npx http-server dist

浏览器控制台打印如下

 

 而后,关闭服务,应用程序还在正常运行。此时,服务器已经停止了服务, Service Worker 在提供服务。

 

posted @ 2020-02-04 17:31  cecelia  阅读(908)  评论(0编辑  收藏  举报