vue 部署上线清除浏览器缓存

vue 部署上线清除浏览器缓存

  本文借鉴https://blog.csdn.net/weixin_43299180/article/details/116271209

  vue 项目打包上线之后,每一次都会有浏览器缓存问题,需要手动的清除缓存。这样用户体验非常不好,所以我们在打包部署的时候需要尽量避免浏览器的缓存。下面是我的解决方案:

一、修改根目录index.html

在 head 里面添加下面代码

<meta http-equiv="pragram" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">

  这种会让所有的css/js资源重新加载

二、配置 nginx 不缓存 html

  vue默认配置,打包后css和js的名字后面都加了哈希值,不会有缓存问题。但是index.html在服务器端可能是有缓存的,需要在服务器配置不让缓存index.html

server {
listen 80;
server_name yourdomain.com;
location / {
    try_files $uri $uri/ /index.html;
    root /yourdir/;
    index index.html index.htm;

    if ($request_filename ~* .*\.(?:htm|html)$)
    {
        add_header Cache-Control "no-cache, no-store";  //对html文件设置永远不缓存
    }  
  }
}

  no-cache浏览器会缓存,但刷新页面或者重新打开时 会请求服务器,服务器可以响应304,如果文件有改动就会响应200
  no-store浏览器不缓存,刷新页面需要重新下载页面

三、打包的文件路径添加时间戳

  1、在 vue-cli2.x 创建的项目里,找到 build/webpack.prod.conf.js 文件

//定义一个变量获取当前时间戳
const version = new Date().getTime();
//output模块将时间戳加入到输出的文件名里
output: {
  publicPath: '/',
  path: config.build.assetsRoot,
  filename: utils.assetsPath(`js/[name].[chunkhash].${version}.js`),
  chunkFilename: utils.assetsPath(`js/[id].[chunkhash].${version}.js`)
},

//css文件名加时间戳
new ExtractTextPlugin({
    filename: utils.assetsPath(`css/[name].[contenthash].${version}.css`),
    allChunks: true,
}),

  2、在 vue-cli3.x 创建的项目里,打开 vue.config.js 文件 ( 没有该文件自己在 src 同级目录下创建一个 )

const version = new Date().getTime();
module.exports = {
  	outputDir: 'dist', //打包的时候生成的一个文件名
	lintOnSave: false,
  	productionSourceMap: false,
  	css: {
	    loaderOptions: {
	      sass: {
	        data: `@import "@/components/themes/_handle.scss";`
	      }
	    },
	    // 是否使用css分离插件 ExtractTextPlugin
	    extract: {
	      // 修改打包后css文件名   // css打包文件,添加时间戳
	      filename: `css/[name].${version}.css`,   
	      chunkFilename: `css/[name].${version}.css`
	    }
	 },
  	configureWebpack: {
		output: { // 输出重构  打包编译后的 文件名称  【模块名称.版本号.时间戳】
		     filename: `js/[name].[chunkhash].${version}.js`,
		     chunkFilename: `js/[id].[chunkhash].${version}.js`
		}
	}
}
四、location.reload() 重新加载当前文档

  如果index.html 设置了不允许缓存,每次刷新时,就会重新加载资源,可能会造成响应过慢的现象。所以引入了一种新的方案:
  第一步:在package.json文件中,有个属性:version,每次打包时,改变一下内容

  第二步:在main.js文件中,加入如下代码:

const VUE_APP_VERSION = require('../package.json').version
const vers = window.localStorage.getItem("appVersion");
if(VUE_APP_VERSION != vers){
  localStorage.clear()
  window.localStorage.setItem("appVersion", VUE_APP_VERSION);
  location.reload()
}
  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值