前端项目部署缓存问题

90 阅读1分钟

原文章地址: juejin.cn/post/709121…

解决方案 index.html缓存 我们为了避免index.html出现缓存,我们可以通过在head标签中添加meta即可。在前面我们知道当expires设置为0后,以及设置cache-control为no-cache。浏览器当访问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">

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`,
        }
      });
  }
}

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

server {
    location = / {
        try_files $uri /index.html;
        add_header Cache-Control 'no-cache, no-store';
    }
 }