4

uni-app开发微信公众号H5时防止页面被缓存的处理

 2 years ago
source link: http://xuedingmiao.com/blog/uniapp_avoid_cache.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

记录在使用 uni-app 开发公众号应用时防止被缓存的方法

# 背景

修改页面后重新打包,测试人员在确认问题时总是说没改,页面没有变化,需要进行繁琐的清缓存操作才能获取到最新版本。

# 解决方法

确定需要修改的文件,首先我们要看 src/manifest.json 里面定义的 template 字段,根据值找到模板文件。

例如: public/index.html

缓存的文件主要是 css 和 js 两种,所以我们要分别处理。

# 样式缓存处理

我们只需要修改模板文件中引用 css 的地方,在引用 css 文件名的前面加入哈希。类似下面这种方式:


<link
  rel="stylesheet"
  href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css"
/>

如果已经自带了这个哈希值则不用做这个处理。

# JS 缓存处理

修改入口页面的 js 引用机制,加入时间戳。

具体要在项目根目录下添加一个 vue.config.js 配置,需要你的 APP 是命令行创建的,这样在服务器上打包的时候才可以加载使用。

然后输入如下内容:

if (process.env.UNI_PLATFORM === 'h5') {
  let filePath = 'static/js/'
  let Timestamp = new Date().getTime()
  module.exports = {
    // webpack配置
    filenameHashing: false,
    configureWebpack: {
      // webpack 配置 解决js缓存的问题
      output: {
        // 输出重构  打包编译后的 文件目录/文件名称?v=时间戳
        filename: `${filePath}[name].js?v=${Timestamp}`,
        chunkFilename: `${filePath}[name].js?v=${Timestamp}`,
      },
    },
  }
} else {
  // 其他打包配置
  module.exports = {
    // webpack 相关配置
    filenameHashing: false,
  }
}

这样在打包的时候就会在引用的页面 js 后面跟上版本,从而使微信浏览器在每次发布后都加载新的页面 js 保证最新。

# 参考资料


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK