PWA
1 初始化项目
vue create vue-pwa
2 ionic的路由依赖于vue-router,所以接下来安装 vue-router:
vue add router
3 安装ionic
npm install @ionic/vue
4 在main.js引用ionic
import Ionic from ‘@ionic/vue‘ import ‘@ionic/core/css/ionic.bundle.css‘ Vue.use(Ionic)
5 在router.js中使用IonicVueRouter替换vue router
import Vue from ‘vue‘
import { IonicVueRouter } from ‘@ionic/vue‘;
import Home from ‘./views/Home.vue‘
Vue.use(IonicVueRouter)
export default new IonicVueRouter({
mode: ‘history‘,
base: process.env.BASE_URL,
routes: [
{
path: ‘/‘,
name: ‘home‘,
component: Home
}
]
})6 修改App.vue内容为
<template>
<div id="app">
<ion-app>
<ion-vue-router/>
</ion-app>
</div>
</template>7 可以运行 yarn serve看效果
如果页面报这个错误

可以安装这个版本
yarn add
页面就可以运行起来了

8 在项目中实现业务代码
。。。。。。
9 实现PWA
使用现成的@vue/pwa插件来给我们的项目增加pwa功能。安装@vue/pwa:
vue add @vue/pwa
10 安装完成后在项目的public中增加manifest.json文件,文件内容如下:
{
"name": "vue-ionic-pwa",
"short_name": "vue-ionic-pwa",
"icons": [
{
"src": "./img/icons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "./img/icons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "./index.html",
"display": "standalone",
"background_color": "#000000",
"theme_color": "#4DBA87"
}manifest.json中主要包含app的基本信息,比如名称(name)、图标(icons)、显示方式(display)等等,是web app能被以类似原生的方式安装、展示的必要配置。更多的配置项可参考 MDN Web App Manifest。
重新yarn serve启动项目后,在Chrome浏览器控制台中也可看到app的manifest配置:

11 添加registerServiceWorker.js
registerServiceWorker.js用于注册service worker。service worker通俗来讲就是在浏览器后台独立于网页运行的一段脚本,service worker可以完成一些特殊的功能,比如:消息推送、后台同步、拦截和处理网络请求、管理网络缓存等。Service worker之于pwa的意义在于能够为用户提供离线体验,即掉线状态下用户依旧能够访问网站并获取已被缓存的数据。使用service worker需要HTTPS
registerServiceWorker.js
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)
}
})
}在本地启动项目,在Chrome浏览器控制台中看不到service worker的状态。由于@vue/cli-plugin-pwa生成的service worker只在生产环境生效,所以建议将项目build之后部署到生产环境测试。本文示例使用 github pages进行部署和展示(页面下边Tip1有部署的具体步骤)。
Tip1
首先在GitHub上新建一个仓库,命名为username.github.io(username是GitHub的用户名)https://pages.github.com/
把本地项目上传到上边新建的git仓库