Fork me on Bolg '◡'

Vue项目部署上线清理浏览器缓存

场景描述

为什么前端部署后会有缓存呢?原因有以下几种:

  1. index.html由于是在打包的时候处在public文件夹下,所以他的文件是不变得。所以会有缓存存在
  2. js,以及css文件采用默认的打包机制,只是文件增加hash值,在某种情况下会存在hash值不变导致的缓存
  3. 服务器缓存

解决方案

1 index.html 缓存解决
通过在head标签中添加meta即可,浏览器当访问index.html的时候,会去服务器咨询服务器是否需要更新。服务器走协商缓存处理逻辑,代码如下:

<meta http-equiv="pragram" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="expires" content="0">
  1. js和css缓存
    在webpack中,我们可以通过配置output来管理输出,因此我们只需要在vue.config.js配置文件中将output修改,就能满足了。如何能保证输出的文件名是不会相同的呢,最简单的方法就是使用时间戳的方式。代码如下:
const version = new Date().getTime();
module.exports = {
    configureWebpack: config => {
      Object.assign(config,{
        entry: {
          app: '/src/main.ts'
        },
        output:{
          ...config.output,
          filename:`static/js/[name].[hash].${version}.js`,
          chunkFilename:`static/js/[name].[hash].${version}.js`,
        }
      });
  }

3.服务器缓存
由于我们现在大都采用nginx进行服务转发,所以有的时候会存在nginx缓存、所以我们只需要在nginx.conf文件增加Cache-Control配置即可。代码如下:

        location ~* \.(htm|html)$ {
            root   html;
            expires -1;
            add_header Cache-Control no-store;
            add_header Pragma no-cache; 
        } 

但是如果这样设置后,其实可以理解为每次都需要去咨询服务器是否更新,这样每次刷新页面的时候,会导致加载时间太长。各位酌情加

至此vue项目部署上线需要清理缓存问题解决了。

本文源自:https://juejin.cn/post/7091213810773540878

posted @ 2022-12-07 10:42  webhmy  阅读(3604)  评论(0编辑  收藏  举报