首页 > 解决方案 > Gatsby 在生产环境中禁用缓存

问题描述

当您将 Gatsby 应用程序构建到生产版本中时,您将在控制台中看到以下内容:

success Caching JavaScript and CSS webpack compilation - 25.915s
success Caching HTML renderer compilation - 14.491s

Gatsby 缓存了一些构建的文件,这样子序列构建会更快。问题是,我正在将我的项目部署到不支持缓存的服务。部署后,一切都将被丢弃。所以把 20% 的构建时间花在缓存上是没有意义的。

有谁知道如何在构建生产构建时禁用缓存?

标签: reactjsgatsby

解决方案


有两种方法(据我所知)可以做到这一点,或者至少你可以尝试:

  • 在您gatsby-node.js使用onPostBuildAPI 调用中,其中设置了缓存管理:

    exports.onPostBuild = async function ({ cache, graphql }, { query }) {
       const cacheKey = "some-key-name"
       const twentyFourHoursInMilliseconds = 24 * 60 * 60 * 1000 // 86400000
       let obj = await cache.get(cacheKey)
    
       if (!obj) {
         obj = { created: Date.now() }
         const data = await graphql(query)
         obj.data = data
       } else if (Date.now() > obj.lastChecked + twentyFourHoursInMilliseconds) {
         /* Reload after a day */
         const data = await graphql(query)
         obj.data = data
       }
    
       obj.lastChecked = Date.now()
    
       await cache.set(cacheKey, obj)
    
       /* Do something with data ... */
    }
    

    您可以尝试在缓存起作用之前返回/跳过该功能。

  • 尝试使用 Gatsby 标志:

    module.exports = {
       flags: {
         PRESERVE_WEBPACK_CACHE: false,
         PRESERVE_FILE_DOWNLOAD_CACHE: false
       },
       plugins: [...]
    }
    

    在这种情况下,PRESERVE_WEBPACK_CACHE可能PRESERVE_FILE_DOWNLOAD_CACHE对您有用(相关的伞形问题)。

也许你可以开始用这些方法拉线。


推荐阅读