1、通过vue-cli脚手架进行安装pwa插件
vue add pwa
2、此时会生成registerServiceWorker.js或者manifest.json两个文件。(如果没有manifest.json文件,在public里面自己新建)
配置manifest.json文件.(manifest.json文件主要是配置图标,app名称,显示方式等)manifest.json参考链接
基本配置 使用时需要把注释删掉
{
"name": "wc--movies",// 导航显示的名字
"short_name": "wc", // app的名字
"start_url": ".",
"icon": [
{
// app图标,会根据不一样的系统进行适配
"src": "/public/img/icons/android-chrome-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "/public/img/icons/android-chrome-192x192.png",
// 大小
"sizes": "192x192",
// 格式
"type": "image/png"
}],
//导航界面的背景颜色
"background_color": "white",
//手机最上方显示运营商及电量、时间等这一栏的颜色
"theme_color": "white",
//页面显示效果为没有地址栏和底部状态栏
"display": "standalone"
}
- 在index.html中引入manifest.json
<link rel="manifest" href="/manifest.json">
4、 registerServiceWorker.js文件(registerServiceWorker.js主要是注册Service Worker。SW可以用于消息推送,缓存管理、后台同步、拦截和处理网络请求等。注意:使用SW需要https及浏览器兼容)
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready () {
console.log(
'App is being served from cache by a service worker.\n' +
'For more details, visit https://goo.gl/AFskqB'
)
},
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.')
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
}
5、配置vue.config.js文件,控制Service Worker行为。设置缓存逻辑、文件名字等。参考@vue/cli-plugin-pwa及workbox参考
pwa: {
workboxPluginMode: 'GenerateSW', // 也可以定义为‘InjectManifest’模式。但是需自己写SW.js文件进行配置
workboxOptions: {
importWorkboxFrom: 'cdn', //从''cdn"导入workbox,也可以‘local’
skipWaiting: true, // 安装完SW不等待直接接管网站
clientsClaim: true,
navigateFallback: '/index.html',
exclude: [/\.(?:png|jpg|jpeg|svg)$/], //在预缓存中排除图片
// 定义运行时缓存
runtimeCaching: [
{
urlPattern: new RegExp('^https://cdn'),
handler: 'NetworkFirst',
options: {
networkTimeoutSeconds: 20,
cacheName: 'cdn-cache',
cacheableResponse: {
statuses: [200]
}
}
}
]
}
}