You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gatsby中配置JS、CSS静态资源缓存解决页面重载空白问题

Gatsby静态资源缓存配置方案

核心说明

  • 你需要的Cache-Control响应头不需要通过第三方Gatsby插件实现,属于部署服务器层面的配置,Gatsby构建生成的带hash后缀的静态资源天然适配immutable缓存策略
  • 你提到的node_modules相关资源会被Gatsby构建打包到带hash的JS/CSS文件中,不需要单独针对node_modules做特殊处理

不同部署场景的配置方式

Nginx部署

在Nginx站点配置的server块中添加以下规则:

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    expires 1y;
}

配置完成后执行nginx -s reload生效即可。

Vercel部署

在项目根目录新建vercel.json文件,添加以下内容:

{
  "headers": [
    {
      "source": "/(.*).(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, max-age=31536000, immutable"
        }
      ]
    }
  ]
}

Netlify部署

在项目根目录新建_headers文件,添加以下内容:

/*.js
  Cache-Control: public, max-age=31536000, immutable
/*.css
  Cache-Control: public, max-age=31536000, immutable
/*.(png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)
  Cache-Control: public, max-age=31536000, immutable

重载空白问题优化

你当前gatsby-plugin-offline的precache范围仅覆盖了/projects/路径,可调整配置扩大预缓存范围,减少重载时资源加载等待导致的空白:

{
  resolve: `gatsby-plugin-offline`,
  options: {
    precachePages: ['/', '/projects/*'], // 可按你的实际页面路径调整,支持通配符匹配
  },
}

内容的提问来源于stack exchange,提问作者bruce lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:09:01