首页 > 解决方案 > 重置生产 create-react-app 应用程序的浏览器缓存

问题描述

因此,目前我在 Amazon S3 上托管了一个 React 应用程序,它通过 Cloudfront CDN 提供服务,但是,我制作的每个新的生产版本,最终用户都必须深度刷新(ctrl+shift+r)整个页面(因为 prev 构建的内容保留在浏览器缓存)。只有在制作生产版本时,我才能使 CDN 缓存和浏览器缓存失效。我使用GitLab ci 顺便说一句。

标签: amazon-s3create-react-appamazon-cloudfrontbrowser-cache

解决方案


我们在 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,js,gif,jpeg,jpg,png,svg,webp,ttf,woff,woff2,wasm}';
  const cachedTypes = '**/*.{ico}';
  const noCacheTypes = '**/*.{html,json,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 脚本一起使用。


推荐阅读