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:
![danielbayerlein](https://res.cloudinary.com/practicaldev/image/fetch/s--X6HO7H85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--_QuA6QVY--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/4277/c93c2ded-c4df-4de0-a3f6-6c48af19cbb6.jpg)
Incremental Gatsby Builds with GitHub Actions
Daniel Bayerlein ・ Oct 14 '20 ・ 2 min read
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)