HBuilder打包web地址的apk,更新dist后如何自动清缓存

使用HBuilder打包web项目地址的apk,每次更新dist后,打开APP页面一般不会自动更新,需要先清除应用的数据缓存,再打开才会更新,这样很麻烦,那么如何能让APP自动清缓存更新页面呢?

我们需要在打包的配置文件中添加清除缓存的内容

在vite.config.ts中添加配置

复制代码
import { defineConfig } from 'vite'

const viteConfig = defineConfig(async ({ mode }) => {
	return {
		build: {
			outDir: "dist",
			// 资源文件名带 hash,避免 JS/CSS 被 WebView 长期缓存
			rollupOptions: {
				output: {
					entryFileNames: 'assets/[name]-[hash].js',
					chunkFileNames: 'assets/[name]-[hash].js',
					assetFileNames: 'assets/[name]-[hash][extname]',
				},
			},
		},
		plugins: [
			// 注入版本号,解决缓存问题
			{
				name: 'dm-app-build-version',
				apply: 'build',
				transformIndexHtml(html: string) {
					const buildVersion = `${process.env.npm_package_version || '1.0.0'}-${Date.now()}`;
					const cacheMeta = [
						'<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />',
						'<meta http-equiv="Pragma" content="no-cache" />',
						'<meta http-equiv="Expires" content="0" />',
						`<meta name="app-build-version" content="${buildVersion}" />`,
					].join('\n    ');
					const versionScript = `<script>
(function () {
  if (!window.plus) return;
  var version = '${buildVersion}';
  var storageKey = '__app_build_version__';
  var prevVersion = localStorage.getItem(storageKey);
  var versionChanged = prevVersion && prevVersion !== version;
  localStorage.setItem(storageKey, version);
  if (!versionChanged) return;
  var reload = function () { location.reload(); };
  if (plus.cache && plus.cache.clear) {
    document.addEventListener('plusready', function () {
      plus.cache.clear(reload);
    }, { once: true });
    return;
  }
  reload();
})();
</script>`;
					return html
						.replace('</head>', `    ${cacheMeta}\n</head>`)
						.replace('<body>', `<body>\n    ${versionScript}`);
				},
			},
		],
        //... 其他配置自行添加
    }
});

export default viteConfig

这样在每次打包更新dist后,APP就会自动刷新页面啦。

相关推荐
奔跑的卡卡32 分钟前
线上Web异常发现为什么总是滞后?一套自研Web实时异常分析监控系统整体架构拆解
前端·web安全·架构
梦曦i1 小时前
create-uni-app v1.1.0:结构化生成,工程骨架更规范
前端·uni-app
流光D1 小时前
AI时代,搭建 web 站点并配置 nginx 反向代理流程
运维·服务器·前端·人工智能·nginx·ai·ai编程
PBitW1 小时前
Travel Planner — 智能旅行行程规划助手
前端·后端
梨想橙汁1 小时前
CSS Grid 网格布局:二维布局神器,轻松实现复杂网页排版
前端·css
lhldsg1 小时前
酒吧点餐小程序开发:从需求分析到技术落地实战
java·前端·小程序·架构·交友
Csvn1 小时前
微前端样式隔离:为什么你的 CSS 串到别人家了?Shadow DOM、CSS Variables 与 @layer 实战
前端
金花顺1 小时前
android_media_AudioTrack
前端·面试
木公子1 小时前
Vue3源码精读04:Scheduler 调度器深度解析|异步批量更新与任务队列源码全解
前端·vue.js