【问题标题】:How to change cache polilcy for static assets in React app (created with create-react-app)如何在 React 应用程序中更改静态资产的缓存策略(使用 create-react-app 创建)
【发布时间】:2020-05-02 21:05:05
【问题描述】:

我使用 React.js(使用 create-react-app)创建了一个应用程序,但我找不到更改静态资产的缓存策略(我对 max-age 感兴趣)的方法。默认情况下,我的应用程序的静态资产(包括当我使用带有“npm run build”的生产构建时)的 max-age 为 0。

我在官方 create-react-app 文档中找到的是:https://create-react-app.dev/docs/production-build/#static-file-caching

它没有帮助我更改静态资产的缓存策略(我有图片)。

我还尝试使用“fetch”方法并设置自定义标头,但最终得到了重复值“max-age=99999,max-age=0”。在缓存策略方面,create-react-app 似乎绕过了您的自定义标头。

如何设置自定义标题?提前致谢!

【问题讨论】:

    标签: javascript reactjs caching service-worker create-react-app


    【解决方案1】:

    如果您的 Web 服务器无法设置这些标头,WorkboxService Worker patterns 将是您进行客户端缓存的最佳选择。您是否还能够查看这些 create-react-app 文档?

    1. Proxying API Requests in Development
    2. Deployment

    您也可以尝试using a web server like Nginx to proxy create-react-app,删除其标题,然后添加您自己的:

    location / {
       ...
    
       // hide create-react-app response header
       proxy_hide_header max-age;
    
      // send your own header to client
      add_header max-age 99999;
    }
    

    【讨论】:

    • 感谢您的回复!有没有办法通过开箱即用的 create-react-app 设置标准缓存策略?如果没有,您在上面发布的解决方案之一的变通方法是否容易?
    • 不确定开箱即用的可能性,因为我在节点服务器前使用负载平衡器或 Nginx。用该建议更新了答案。你可以和他们一起search/create and official issue/question。他们是一个非常有帮助的社区
    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2019-07-16
    • 2020-12-10
    • 2019-11-07
    • 2018-09-28
    • 2021-11-10
    相关资源
    最近更新 更多