preface

“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

This article focuses on PWA applications. After reading this article, you will understand

  • What is PWA?
  • Advantages and disadvantages of PWA
  • How do PWA application configuration items work
  • Quickly configure a starting PWA application and debug it locally

Some concepts of PWA

The full name of PWA is Progressive Web Apps

The analogy is: native Web applets

Main advantages

  • Can be actively discovered by the browser
  • Easy to install, the app icon can be sent to the mobile desktop on the phone, the browser can be installed on the computer
  • Network independent, offline access, active push messaging, resource pre-caching and offline priority
  • Progressive, downward compatible
  • Responsive, multi-terminal adaptation

Major disadvantages

  • Browser compatibility is poor. Currently, this feature is supported only by the latest versions of Chrome, Firefox, and Edge

Problem solved

How to cache web resources correctly and make them available offline

It mainly makes use of the capability of the Service Worker provided by the browser. The Service Worker runs on a thread independent from the main JavaScript thread of the page and can control network requests, message push and perform specified tasks. The ability to control network requests enables offline page access. The Service Worker explained

Configuration of three elements

  • reliableHttpsNetwork protocol
  • service-worker.js
  • manifest.json

More complete Information: Progressive Web Applications (PWA)

Rapid configuration

How to configure PWA application using WebPack

Quickly create a WebPack configuration project

The directory structure is as follows

|-- my-pwa-app
    |-- .gitignore
    |-- index.html
    |-- package-lock.json
    |-- package.json
    |-- webpack.config.js
    |-- src
        |-- main.js
        |-- assets
            |-- logo.png
Copy the code

Once created, we install the key dependency packages

  • workbox-webpack-pluginUsed to generateservice-worker.jsfile
  • webpack-pwa-manifestUsed to generatemanifest.jsonfile
  • register-service-workerUsed to help us register quicklyservice-worker.jsfile
npm install workbox-webpack-plugin webpack-pwa-manifest -D

npm install register-service-worker
Copy the code

First configure workbox-webpack-plugin and register-service-worker

// webpack.config.js
/* * @Date: 2021-11-03 21:43:51 * @LastEditors: cunhang_wwei * @LastEditTime: 2021-11-03 22:19:43 * @Description: Webpack packages files */
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WorkboxWebpakcPlugin = require('workbox-webpack-plugin');

module.exports = {
    mode: 'production'.entry: './src/main.js'.plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        }),
        new WorkboxWebpakcPlugin.GenerateSW({
            skipWaiting: true.clientsClaim: true})].output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'}};Copy the code
// register-service-worker.js
/* * @Date: 2021-11-03 22:20:06 * @LastEditors: cunhang_wwei * @LastEditTime: 2021-11-03 22:21:24 * @Description: Registration service - worker * /

import { register } from "register-service-worker";

register('/service-worker.js', {
    registrationOptions: { scope: '/' },
    ready(registration) {
        console.log('Service worker is active.')},registered(registration) {
        console.log('Service worker has been registered.')},cached(registration) {
        console.log('Content has been cached for offline use.')},updatefound(registration) {
        console.log('New content is downloading.')},updated(registration) {
        console.log('New content is available; please refresh.')},offline() {
        console.log('No internet connection found. App is running in offline mode.')},error(error) {
        console.error('Error during service worker registration:', error)
    }
})
Copy the code
// main.js
/* * @date: 2021-11-03 21:53:07 * @lasteditors: Cunhang_wwei * @LasteditTime: 2021-11-03 22:23:31 * @description: Main entry */

import './register-service-worker'

const name = 'pwa app'

console.log(name);
Copy the code

We packaged the project with an NPM Run build and ran it in a browser (see my previous article on how to quickly start a locally packaged Vue or React file).

We see that the service-worker has started working

Our PWA application configuration is half complete!

However, the browser cannot recognize that this is a PWA application because manifest.json is not configured

Configuration webpack – pwa – the manifest

// webpack.config.js
plugins: [
    new HtmlWebpackPlugin({
        template: './index.html'
    }),
    new WorkboxWebpakcPlugin.GenerateSW({
        skipWaiting: true.clientsClaim: true
    }),
    // Note that WebpackPwaManifest needs to be executed after HtmlWebpackPlugin
    new WebpackPwaManifest({
        name: 'My Progressive Web App'.short_name: 'MyPWA'.description: 'My awesome Progressive Web App! '.theme_color: '# 123124'.background_color: '# 111'.crossorigin: 'use-credentials'.//can be null, use-credentials or anonymous
        icons: [{src: path.resolve('src/assets/logo.png'),
                sizes: [192.512] // multiple sizes}]})],Copy the code

We packaged yarn Build again and found that the manifest.json file was generated

There are also more
and tags in index. HTML

We’re running it in the browser

See that the browser has recognized manifest.json, and the address bar has a shortcut to bookmark as an application

Our PWA application configuration is done ✨

Summary and review

Configuration of three elements

  • reliableHttpsNetwork protocol
  • service-worker.js
  • manifest.json

Configure three musketeers

  • service-work.jsFile byworkbox-webpack-pluginGenerate, defineService WorkerHow to work
  • webpack-pwa-manifestPlug-ins need to be configured inhtml-webpack-pluginAfter the plug-in.webpack-pwa-manifestPlug-in,html-webpack-pluginPlug-in generatedhtmlFile before, according to the configurationPWAInformation, added<meta>and<link>The label
  • register-service-workerwillservice-worker.jsRegister in the browser

QA

  • How do I know if this is a fully configured PWA application?
    • F12Inside the debug consoleLighthouseCan detect if a PWA application is properly configured
  • What is the difference between the PWA application cache and the browser cache?
    • service-workerYou can listenfetchEvent and hijack the browser request, the browser cache relies on the request header field.service-workerResources can be pulled according to the configuration for subsequent use. The browser cache only controls the requested resource files, not all resources

The last

This article starts from the concept of PWA, to help you quickly configure the entry PWA application, the application has the ability to pre-cache resources, offline loading and active browser recognition.

The configuration of a good PWA application still involves difficulties such as message push, message subscription and offline data reuse. There is still a long way to go. I hope this article can play a role in casting jade.

If you find this article helpful, don’t forget to like 👍!

Code repository address: github.com/AFine970/my…

Good study will not be bad, I am 970, we progress together!