解决VUE3项目部署后存在缓存页面不更新的问题

方法一:

找到项目中的index.html文件,在头部加上以下代码

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">

若以上代码仍不能解决问题,请使用以下两种方法。

方法二:

此方法适用于路由为hash模式的情况下

找到配置文件,在文件vue.config.js中配置filenameHashing和output。

1.filenameHashing(关闭hash命名)

2.通过output配置filename和chunkFilename之后使得打包后生成的html中引入的js地址后面有版本号,由此触发更新,版本号可以是固定值。

注意:路径的配置因项目的配置而异,不要出错!

module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  publicPath: "./",
  assetsDir: 'static',
  filenameHashing: false,
  configureWebpack: {
    output: {
      filename: `static/js/[name].js?v=1`,
      chunkFilename: `static/js/[name].js?v=1`
    }
  },
})   

打包后代码和浏览器中效果如下:

方法三:

此方法适用于路由为history模式的情况下

通过时间戳配置js文件名和css文件名,使得每次打包生成的文件名不同,从而触发更新。

注意:history模式需要服务器端的支持,若服务器端不支持,会出现404的现象。

const { defineConfig } = require('@vue/cli-service')
const Timestamp = new Date().getTime();

module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  publicPath: "./",
  assetsDir: 'static',
  configureWebpack: {
    output: {
      filename: `static/js/[name].${Timestamp}.js`,
      chunkFilename: `static/js/[name].${Timestamp}.js`
    }
  },
  css: { 
    extract: { 
      filename: `static/css/[name].${Timestamp}.css`,
      chunkFilename: `static/css/chunk.[id].${Timestamp}.css`,
    }
  }
}) 

以上方法效果因项目而异,要注意和其它配置项的关联。

猜你喜欢

转载自blog.csdn.net/weixin_44594219/article/details/132696826