使用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就会自动刷新页面啦。