新的vue脚手架已经可以自带pwa了,本文主要针对旧版的webpack。
先装三个插件:
$npm i register-service-worker sw-precache-webpack-plugin webpack-pwa-manifest --save-dev
因为pwa主要用于生产,我们来动手改造 build/webpack.prod.conf.js,
首先在头部引入两个插件:
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin') const WebpackPwaManifest = require('webpack-pwa-manifest')
在 plugins 加入:
plugins: [ new SWPrecacheWebpackPlugin({ cacheId: 'my-project-name', filename: 'service-worker.js', staticFileGlobs: ['dist/**/*.{js,html,css}'], minify: true, stripPrefix: 'dist/' }),
new WebpackPwaManifest({ name: 'My Progressive Web App', short_name: 'MyPWA', description: 'My awesome Progressive Web App!', background_color: '#ffffff', crossorigin: 'use-credentials', //can be null, use-credentials or anonymous icons: [ { src: path.resolve('src/assets/icon.png'), sizes: [96, 128, 192, 256, 384, 512] // multiple sizes }, { src: path.resolve('src/assets/large-icon.png'), size: '1024x1024' // you can also use the specifications pattern } ] }),
// ...
]
这个时候打包出来的代码根目录里面多了个 service-worker.js ,html文件里面 pwa 相关元素也加上了。
添加一个文件用来注册 serviceWorker,(眼熟吗?抄的vue-cli 3 ^_^)
// serviceWorker.js import { register } from 'register-service-worker' if (process.env.NODE_ENV === 'production') { register('service-worker.js', { ready () { console.log( 'App is being served from cache by a service worker.' ) }, registered () { console.log('Service worker has been registered.') }, cached () { console.log('Content has been cached for offline use.') }, updatefound () { console.log('New content is downloading.') }, updated () { console.log('New content is available; please refresh.') window.location.reload(true) // 这里需要刷新页面 }, offline () { console.log('No internet connection found. App is running in offline mode.') }, error (error) { console.error('Error during service worker registration:', error) } }) }
在入口 main.js 引入该文件:
import './serviceWorker'
至此,改造完成。