问题描述
因此,目前我在Amazon S3上托管了一个React应用程序,并且该应用程序通过Cloudfront CDN提供服务,但是,我制作的每个新生产版本中,最终用户都必须深度刷新(ctrl+shift+r
)整个页面(因为prev构建的内容保留在浏览器缓存中)。仅在发布生产版本时,我才能使CDN缓存和浏览器缓存无效吗?我使用 GitLab ci btw。
解决方法
我们在gulp中使用AwsPublish插件。 这是gulp文件的代码
const day = 86400;
const farFuture = { 'Cache-Control': `max-age=${day * 365}` };
const future = { 'Cache-Control': `max-age=${day * 7}` };
const noCache = { 'Cache-Control': 'no-cache' };
const gzipTypes = '**/*.{html,css,js,svg,ico,json,txt,wasm,map,mem}';
const cacheBustedTypes = '**/*.{css,gif,jpeg,jpg,png,webp,ttf,woff,woff2,wasm}';
const cachedTypes = '**/*.{ico}';
const noCacheTypes = '**/*.{html,xml,txt}';
const otherTypes = ['**/*',`!${cacheBustedTypes}`,`!${cachedTypes}`,`!${noCacheTypes}`];
const publisher = $.awspublish.create(awsSettings);
const options = {
force,};
return gulp
.src(source,{ base })
.pipe($.if(gzipTypes,$.awspublish.gzip()))
.pipe($.if(cacheBustedTypes,publisher.publish(farFuture,options)))
.pipe($.if(cachedTypes,publisher.publish(future,options)))
.pipe($.if(noCacheTypes,publisher.publish(noCache,options)))
.pipe($.if(otherTypes,publisher.publish(null,options)))
.pipe($.if(sync,publisher.sync()))
.pipe($.awspublish.reporter());
});
以noCacheTypes类型添加index.html。 Webpack将为css和js文件生成chunkhash,更改它们后,缓存将被破坏。 我们正在使用github动作以及该gulp脚本。