19. webpack优化配置-PWA 渐进式网络应用开发程序

渐进式网络应用程序(Progressive Web Application - PWA),在离线(offline)时应用程序能够继续运行功能。

https://www.webpackjs.com/guides/progressive-web-application/

serviceWorker代码必须运行在服务器上

需要的插件:workbox-webpack-plugin

  1. 下载插件workbox-webpack-plugin

    npm i workbox-webpack-plugin -D
    
  2. 在webpack配置文件webpack.config.js中进行配置

    const path = require('path');
    
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const WorkboxWebpackPlugin = require("workbox-webpack-plugin")
    
    module.exports = {
          
          
        mode: 'production',
        entry: './src/js/index.js',
        output: {
          
          
            filename: 'js/[name][contenthash:8].js',
            path: path.resolve(__dirname, 'bulid'),
        },
        plugins: [
            new HtmlWebpackPlugin({
          
          
                template: './src/index.html'
            }),
            new WorkboxWebpackPlugin.GenerateSW({
          
          
                // ServiceWorkers 快速启用
                // 不允许遗留任何“旧的” ServiceWorkers
                clientsClaim: true,
                skipWaiting: true
            })
        ]
    }
    
  3. 在入口文件index.js中注册Service Worker

    //如果浏览器支持serviceWorker 则使用
    if ('serviceWorker' in navigator) {
          
          
        window.addEventListener('load', () => {
          
          
            navigator.serviceWorker.register('/service-worker.js').then(registration => {
          
          
                console.log('如果浏览器支持serviceWorker注册成功', registration);
            }).catch(registrationError => {
          
          
                console.log('SW registration failed: ', registrationError)
            })
        });
    }
    
  4. 如果开启eslint检查语法,可能会报不认识window,navigator等错误需要修改package.json中eslint的相关配置,将browser设置为true

    "eslintConfig": {
          
          
        "extends": "airbnb-base",
        "browser": true
      }
    
  5. 打包

    webpack
    
  6. 在服务器端查看

猜你喜欢

转载自blog.csdn.net/kouzuhuai2956/article/details/108092801