资讯专栏INFORMATION COLUMN

为 VUE 项目添加 PWA 解决发布后刷新报错问题

lifefriend_007 / 2835人阅读

摘要:为了解决这个问题,我的解决方案是使用,这样就可以将缓存到本地,再次发布后,会使旧的失效,重新请求并缓存。结语几分钟就搞定了,然后把之前的一个基于的后台模板项目也升级了,如果有相同需求的可以参考下。

为什么要给 VUE 项目添加 PWA
为什么要添加?因为不管是部署在 IIS,还是 nginx,每次应用部署后,再次访问因为旧的 js 已经不存在,所以页面访问的时候会整个报错,报错的结果就是一个白屏。   
为了解决这个问题,我的解决方案是使用 PWA ,这样就可以将 js 缓存到本地,再次发布后,service-worker.js 会使旧的 js 失效,重新请求并缓存 js。

如果对于问题这个有更好的解决方案,务必请大佬指定一二

安装 PWA 的相关依赖包

yarn 安装

yarn add sw-precache-webpack-plugin --dev
yarn add uglify-es --dev

npm 安装

npm install sw-precache-webpack-plugin --dev-dev
npm install uglify-es --dev-dev
添加修改相关配置

下面这些文件忘记出处是哪,Github也能搜到一些,之前写的 PWA 的 Demo 里面拿过来的~

添加 build/service-worker-dev.js
self.addEventListener("install", () => self.skipWaiting())

self.addEventListener("activate", () => {
  self.clients.matchAll({ type: "window" }).then(windowClients => {
    for (let windowClient of windowClients) {
      // Force open pages to refresh, so that they have a chance to load the
      // fresh navigation response from the local dev server.
      windowClient.navigate(windowClient.url)
    }
  })
})
添加 build/service-worker-prod.js
;(function() {
  "use strict"

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors.
  var isLocalhost = Boolean(
    window.location.hostname === "localhost" ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === "[::1]" ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
  )

  window.addEventListener("load", function() {
    if (
      "serviceWorker" in navigator &&
      (window.location.protocol === "https:" || isLocalhost)
    ) {
      navigator.serviceWorker
        .register("service-worker.js")
        .then(function(registration) {
          // updatefound is fired if service-worker.js changes.
          registration.onupdatefound = function() {
            // updatefound is also fired the very first time the SW is installed,
            // and there"s no need to prompt for a reload at that point.
            // So check here to see if the page is already controlled,
            // i.e. whether there"s an existing service worker.
            if (navigator.serviceWorker.controller) {
              // The updatefound event implies that registration.installing is set
              var installingWorker = registration.installing

              installingWorker.onstatechange = function() {
                switch (installingWorker.state) {
                  case "installed":
                    // At this point, the old content will have been purged and the
                    // fresh content will have been added to the cache.
                    // It"s the perfect time to display a "New content is
                    // available; please refresh." message in the page"s interface.
                    break

                  case "redundant":
                    throw new Error(
                      "The installing " + "service worker became redundant."
                    )

                  default:
                  // Ignore
                }
              }
            }
          }
        })
        .catch(function(e) {
          console.error("Error during service worker registration:", e)
        })
    }
  })
})()
添加 build/load-minified.js
"use strict"

const fs = require("fs")
const UglifyJS = require("uglify-es")

module.exports = function(filePath) {
  const code = fs.readFileSync(filePath, "utf-8")
  const result = UglifyJS.minify(code)
  if (result.error) return ""
  return result.code
}
修改 build/webpack.prod.conf.js

首先引用sw-precache-webpack-pluginbuild/load-minified

const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin")
const loadMinified = require("./load-minified")

为 webpack 插件 HtmlWebpackPlugin 添加参数 serviceWorkerLoader: `

  plugins: [
      ....
  new HtmlWebpackPlugin({
      filename:
        process.env.NODE_ENV === "testing" ? "index.html" : config.build.index,
      template: "index.html",
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: "dependency",
      serviceWorkerLoader: ``
    }),

并在最后添加 SWPrecacheWebpackPlugin 插件

// service worker caching
new SWPrecacheWebpackPlugin({
  cacheId: "ysj-admin",
  filename: "service-worker.js",
  staticFileGlobs: ["dist/**/*.{js,html,css}"],
  minify: true,
  stripPrefix: "dist/"
})
在 /index.html 中注入 service-worker.js
<%= htmlWebpackPlugin.options.serviceWorkerLoader %>

如下所示


  
<%= htmlWebpackPlugin.options.serviceWorkerLoader %>

至此,添加完毕,build 之后查看缓存中是否包含 js 检验结果

注意:PWA 应用需要在本地上运行或者 https 协议下, 要保证你的页面是安全页面。
结语

几分钟就搞定了,然后把之前的一个基于VUE的后台模板项目也升级了,如果有相同需求的可以参考下。

仓库地址:https://github.com/yimogit/me...
线上预览:https://vue-admin.yimo.link/

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/97634.html

相关文章

  • 一个 PWA 的诞生

    摘要:不是一个新名词,早在年已经提出这个思想,但是直到的发布,终于可以在中添加到主屏,只有安卓和都能使用的基本功能,它才算是真的开始走近大众。 原文链接:https://ssshooter.com/2018-09... PWA(Progressive Web Apps)虽然是网页应用,但是可以带来媲美原生的用户体验,其中包含离线可用,后台推送等功能。PWA 不是一个新名词,早在 2015 年...

    苏丹 评论0 收藏0
  • Vue全家桶商城全站升级之引入HTTPS,PWA,错误监控,持续构建。

    摘要:免费升级到升级到后,服务器可以开启版本,对比性能和缓存各方面要更好,还有其他新特性,可以启动功能,更好的进行离线缓存,更好的离线体验。 showImg(https://segmentfault.com/img/remote/1460000012773891?w=370&h=661); 在线地址:https://fancy.czero.cn 手机扫描二维码查看: showImg(http...

    zengdongbao 评论0 收藏0
  • 前端每周清单半年盘点之 PWA

    摘要:前端每周清单专注前端领域内容,以对外文资料的搜集为主,帮助开发者了解一周前端热点分为新闻热点开发教程工程实践深度阅读开源项目巅峰人生等栏目。 前端每周清单专注前端领域内容,以对外文资料的搜集为主,帮助开发者了解一周前端热点;分为新闻热点、开发教程、工程实践、深度阅读、开源项目、巅峰人生等栏目。欢迎关注【前端之巅】微信公众号(ID:frontshow),及时获取前端每周清单;本文则是对于...

    崔晓明 评论0 收藏0
  • 前端优化 - 收藏集 - 掘金

    摘要:虽然有着各种各样的不同,但是相同的是,他们前端优化不完全指南前端掘金篇幅可能有点长,我想先聊一聊阅读的方式,我希望你阅读的时候,能够把我当作你的竞争对手,你的梦想是超越我。 如何提升页面渲染效率 - 前端 - 掘金Web页面的性能 我们每天都会浏览很多的Web页面,使用很多基于Web的应用。这些站点看起来既不一样,用途也都各有不同,有在线视频,Social Media,新闻,邮件客户端...

    VincentFF 评论0 收藏0
  • vue从零开发和部署一款移动端pwa单页应用

    摘要:另外,单页应用因为数据前置到了前端,不利于搜索引擎的抓取。所以我们需要对自己的单页应用进行一些优化。 前言 最近秋招之余空出时间来按自己的兴趣动手做了一个项目,一个基于vue-cli3.0, vue,typescript的移动端pwa,现在趁热打铁,将这个项目从开发到部署整个过程记录下来,并将从这个项目中学习到的东西分享出来,如果大家有什么意见或补充也可以在评论区提出。先介绍一下这个项...

    Channe 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<