Gatsby in combination with GraphCMS is really cool, but the build time can be quite long. I've searched for some improvements, which I would like to share with you in this post.
1. Use Conditional Page Builds
Whenever you run gatsby build, all pages are recreated. You can improve the build time by rebuilding only changed pages.
If you're using GitHub Actions, you can check out my previous post:
Use the environment variable GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES in your gatsby build command to enable conditional page builds and persist the .cache and public directories between builds.
GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES=true gatsby develop
2. Parallel processing of GraphQL queries
The default number of parallel GraphQL queries executed by Gatsby is 4. With the environment variable GATSBY_EXPERIMENTAL_QUERY_CONCURRENCY you can increase the number.
GATSBY_EXPERIMENTAL_QUERY_CONCURRENCY=20 gatsby develop
3. Use Query Batching
By default, gatsby-source-graphql executes each query in a separate network request. The plugin offers a configuration option to batch the requests.
If you set GATSBY_EXPERIMENTAL_QUERY_CONCURRENCY to 20 and maxBatchSize to 5, it means that you are running 4 batches in parallel.
{
  resolve: 'gatsby-source-graphql',
  options: {
    typeName: 'GRAPHCMS',
    fieldName: 'graphCmsData',
    url: 'https://api-eu-central-1.graphcms.com/v2/xxxxxx/master',
    batch: true,
    dataLoaderOptions: {
      maxBatchSize: 5
    }
  }
}
  
  
  4. Asynchronize your createPage function
If you use the createPage function to create dynamic pages with GraphCMS, be sure to run this function asynchronously.
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const result = await graphql(...)
  const pages = result.data.graphCmsData.pages.map(async (page) => {
    createPage({
      path: page.slug,
      component: path.resolve('./src/templates/Page.js'),
      context: {
        id: page.id
      }
    })
  })
  await Promise.all([pages])
}
If you have any kind of feedback, suggestions or ideas - feel free to comment this post!
 
 
              
 
     
    
Top comments (0)