如何解决嵌套在公众号里面的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.html 和 version.json 永不被缓存。

相关推荐
全栈弄潮儿²⁰²⁴4 天前
AI Agent 开发实战(30):限流、缓存与成本控制
人工智能·gpt·缓存·agent·限流·agi·成本控制
Together_CZ5 天前
DeepSeek-V4.1-Flash:Pushing the Limits of KV Cache Compression——推动 KV 缓存压缩的极限
缓存·llm·compression·kv cache·deepseek·v4.1-flash·推动 kv 缓存压缩的极限
Pioneer000015 天前
我用 Redis + 网关做多模型 API 路由:缓存命中率 95%+ 的工程实践
人工智能·redis·后端·缓存·性能优化·架构
hweiyu006 天前
Redis命令:MSETNX
redis·缓存
wdfk_prog6 天前
ROS教程08:从 TransportTCP::connect() 追到 TCPROS Connection Header、序列化与 Socket 数据传输
运维·缓存·docker·容器·ros
是Dream呀6 天前
Harness 工程:让 Agent 真正把任务做完
人工智能·分布式·缓存·agent
努力努力再努力wz6 天前
【Redis进阶系列】:从主从复制到 Sentinel,一文建立故障检测、Leader 选举与 Failover 的完整心智模型
数据库·redis·缓存
wdfk_prog7 天前
ROS教程10:从 gtest 到 rostest——Unit Test、Node 集成测试、rosbag 与 rqt 验证闭环
运维·缓存·docker·容器·ros
程序猿乐锅7 天前
【黑马点评 | 第四篇】Redis缓存雪崩
java·数据库·spring boot·redis·缓存
HanhahnaH8 天前
Redis单线程和Tair多线程架构设计对比
分布式·缓存