如何解决嵌套在公众号里面的H5页面有缓存的问题。公众号菜单的H5的域名不希望加版本号去修改

希望实现:检测是否有新的版本,如果有就自动刷新一下页面。

自动化版本注入 + 自动检测更新并刷新页面

1,scripts/set-version.js,(生成 version.json,可供供前端 fetch 使用)

复制代码
// scripts/set-version.js
const { writeFileSync } = require('fs');
const { execSync } = require('child_process');

function getGitCommitHash() {
  try {
    return execSync('git rev-parse --short HEAD').toString().trim();
  } catch (e) {
    console.warn('⚠️ Git not available, using timestamp as fallback');
    return 'unknown';
  }
}

function getBuildTimestamp() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hour = String(now.getHours()).padStart(2, '0');
  const minute = String(now.getMinutes()).padStart(2, '0');
  return `${year}${month}${day}-${hour}${minute}`;
}

const commitHash = getGitCommitHash();
const buildTime = getBuildTimestamp();
const version = commitHash === 'unknown' ? buildTime : `${commitHash}-${buildTime}`;

// 写入 public/version.json(Vite 会原样复制到 dist 根目录)
writeFileSync('./public/version.json', JSON.stringify({ version }, null, 2));

console.log(`✅ Build version generated: ${version}`);

2,vite.config.js(注入全局版本变量)

复制代码
// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { readFileSync } from 'fs';

// 读取 version.json 获取当前版本(确保与 set-version.js 一致)
let APP_VERSION = 'dev';
try {
  const versionFile = JSON.parse(readFileSync('./public/version.json', 'utf-8'));
  APP_VERSION = versionFile.version;
} catch (e) {
  console.warn('⚠️ version.json not found, using "dev" as version');
}

export default defineConfig({
  define: {
    '__APP_VERSION__': JSON.stringify(APP_VERSION)
  },
  plugins: [vue()],
  // 其他配置...
});

3. src/main.js(自动检测并刷新)

复制代码
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';

// ==============================
// 🔁 自动版本检测 & 刷新逻辑
// 放在最顶部!确保早于任何组件加载
// ==============================
(function autoUpdateCheck() {
  // 防止重复执行(如刷新后再次运行)
  if (window.__VERSION_CHECKED__) return;
  window.__VERSION_CHECKED__ = true;

  // 当前本地版本(由 Vite define 注入)
  const currentVersion = __APP_VERSION__;

  // 跳过开发环境(localhost / 127.0.0.1)
  if (
    location.hostname === 'localhost' ||
    location.hostname === '127.0.0.1' ||
    location.protocol === 'file:'
  ) {
    console.log('[Auto Update] Skipped in development mode');
    return;
  }

  // 请求最新版本(加时间戳防缓存)
  fetch('/version.json?t=' + Date.now())
    .then(res => {
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res.json();
    })
    .then(data => {
      const latestVersion = data.version;

      if (latestVersion && latestVersion !== currentVersion) {
        console.log(
          `%c[Auto Update] New version detected!\nLocal: ${currentVersion}\nRemote: ${latestVersion}`,
          'color: #4CAF50; font-weight: bold;'
        );
        // 强制从服务器重新加载(绕过缓存)
        location.reload(true);
      } else {
        console.log('[Auto Update] Already up to date:', currentVersion);
      }
    })
    .catch(err => {
      console.warn('[Auto Update] Check failed, skipping:', err.message);
    });
})();
// ==============================
// 结束自动更新检测
// ==============================

// 正常启动 Vue 应用
createApp(App).mount('#app');

4. 修改 package.json 构建命令

复制代码
{
  "scripts": {
    "dev": "vite",
    "build": "node scripts/set-version.js && vite build",
    "preview": "vite preview"
  }
}

每次 npm run build 会先生成 version.json,再构建

完成前面4个步骤就可以实现:

部署后效果

  • 用户访问 https://your-domain.com/(公众号菜单链接不变)
  • 页面加载 → 自动请求 /version.json
  • 若发现新版本 → 静默刷新一次 → 加载最新代码
  • 用户无感知,始终使用最新版

**后端可以服务端强制禁用缓存:**在你的 Nginx / 服务器配置中,为以下文件禁用缓存:

复制代码
# Nginx 示例
location ~* \.(html|json)$ {
  add_header Cache-Control "no-cache, no-store, must-revalidate";
  add_header Pragma "no-cache";
  add_header Expires "0";
}

确保 index.htmlversion.json 永不被缓存

相关推荐
头顶秃成一缕光3 小时前
Redis + Caffeine 多级缓存架构
redis·缓存·架构
星辰_mya3 小时前
Redis 锁的“续命”艺术:看门狗机制与原子性陷阱
数据库·redis·分布式·缓存·面试
LSL666_4 小时前
Redis值数据类型——list
数据库·redis·缓存·数据类型
尽兴-4 小时前
拨开迷雾:深入理解 Redis 7 的线程模型
数据库·redis·缓存·redis7·线程模型
czlczl200209255 小时前
Redis五种数据类型底层
数据库·redis·缓存
wangjialelele5 小时前
详解Redis终端操作和Redis-plus-plus接口使用
linux·数据库·c++·redis·分布式·缓存·中间件
小璐资源网5 小时前
《Nginx缓存配置:浏览器缓存与服务器缓存实战》
服务器·nginx·缓存
LSL666_6 小时前
Redis值数据类型——String
数据库·redis·缓存·数据类型
最懒的菜鸟19 小时前
redis缓存击穿
数据库·redis·缓存