webpack4.0-PWA的打包配置-12

首先pwa是在服务环境下,进行的,所以先安装一个本地服务, npm i  http-server --save-dev

在package.json中配置,启动服务

{
  "name": "webpack-demo-pwa",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bundle": "webpack",
    "serve": "webpack-dev-server",
    "start": "http-server dist" // 用户启动本地服务,dist指定服务启动的位置
  },
  "author": "ECHO",
  "license": "MIT",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^3.2.0",
    "http-server": "^0.12.1",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1"
  }
}

其次,安装webpack的PWA插件

npm i workbox-webpack-plugin --save-dev

只有线上代码才考虑PWA

webpack.config.js配置

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const WorkboxWebpackPlugin = require('workbox-webpack-plugin') // 用于开启PWA
module.exports = {
    mode:'production',
    entry: {
        main:'./src/index.js'
    },
    output: {
        filename:'[name].[hash].js',
        path:path.resolve(__dirname, 'dist')
    },
    devServer:{
        contentBase: './dist',
        port: 8088,
        open: true
    },
    plugins:[
        new HtmlWebpackPlugin({template: './src/index.html'}),
        new CleanWebpackPlugin({cleanOnceBeforeBuildPatterns: ['**/*', '!static-files*']}),
        new webpack.HotModuleReplacementPlugin(),
        new WorkboxWebpackPlugin.GenerateSW({ // 用于开启PWA
            clientsClaim: true,
            skipWaiting: true
        })
    ],
    optimization:{
        runtimeChunk:{
            name:'runtime'
        }
    }
}

入口文件中业务代码配置,用于判断浏览器是否支持PWA,具体其他配置查看官网

if('serviceWorker' in navigator) { // PWA必须的业务代码,用于判断浏览器是否支持PWA
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js')
        .then(registration => {
            console.log('service-worker registed');
        })
        .catch(error => {
            console.log('service-worker register error');
        })
    })
}
发布了116 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/memedadexixaofeifei/article/details/103905214