另类强刷缓存(了解webpack打包完成的钩子和fs文件写入)

86 阅读1分钟

处理部署还是得用打包的hash+时间戳控制 nginx需要设置index.html入口文件不缓存

// 打包完成时往dist写入json文件
configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    plugins: [
      new CompressionPlugin({
        cache: false, // 不启用文件缓存
        test: /\.(js|css|html)?$/i, // 压缩文件格式
        filename: '[path].gz[query]', // 压缩后的文件名
        algorithm: 'gzip', // 使用gzip压缩
        minRatio: 0.8 // 压缩率小于1才会压缩
      }),
      function () {
        if (process.env.NODE_ENV === 'production') {
          this.hooks.done.tap('BuildTimeJsonPlugin', (stats) => {
            const outputPath = path.resolve(__dirname, 'dist') // 输出目录
            const jsonContent = JSON.stringify({ buildTime }, null, 2)
            // 写入 JSON 文件
            fs.writeFileSync(path.join(outputPath, 'buildTime.json'), jsonContent)
          })
        }
      }
    ],
  },
<script>
    // 在加载html入口文件时判断出强刷页面
    // 如果后面增加了版本更新公告,那就在这种方案的基础上直接增加弹出版本更新公告的功能即可
    // 千万不要使用后端接口来判断是否强刷,那样就太慢了
    // 此函数需要再main.js加载之前就执行
    const buildTime = localStorage.getItem('buildTime')
    const fn = async () => {
      try {
        const res = await fetch('buildTime.json')
        const jsonData = await res.json()
        localStorage.setItem('buildTime', jsonData.buildTime) // 缓存最新的
        if (buildTime && Number(buildTime) !== Number(jsonData.buildTime)) {
          // window.alert('正在清空缓存重新加载页面...')
          window.location.reload(true) // 清空缓存,重新加载页面
        }
      } catch (error) {} // 禁止在public里面有buildTime.json,这个文件是打包的时候自动生成的,本地运行不需要有这个
    }
    fn()
  </script>