How to "fix" Gatsby slow local build times
Ahoy, as the title suggests in this post Iām going to explain one way to resolve the āslow local build timeā issues I know lots of you experience with Gatsby.
Itās worth pointing out that in this post Iāll specifically be referring to sites that source .md
from the local file
system. (Same applies for .mdx
or .json
FYI)
However, Iām pretty confident a similar approach would work when sourcing data from remote sources, be it from your own
implementation of sourceNodes
or perhaps when using one of the many source pluginsā¦ the latter however is 100%
dependant on if the plugin author has exposed a method to limit how much data is being sourced.
If you wanna jump ahead hereās a demo repo: https://github.com/PaulieScanlon/gatsby-slow-local-build-times
How much data is being sourced
In short this is the crux of the problem. If youāre sourcing loads of data the Gatsby build steps are delayed while
Node / gatsby-source-filesystem
do their thing.
In order to speed that bit up itās advised you limit the amount of data youāre sourcing.
gatsby-source-filesystem
This plugin is usually responsible for sourcing files. In the demo repo Iām sourcing Markdown files from the content
directory, and Iād imagine youāll have something similar to the below in your gatsby-config
// gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown-pages`,
path: `${__dirname}/src/content`,
},
},
`gatsby-transformer-remark`,
],
};
The main thing to look at is the path
. The above snippet will source everything from the src/content
directory.
Do you need to source everything
Good question right? Well, in production
, mostly likely the answer will be yes. In development
however, probably
not.
** This was my penny drop moment! **
I have to admit Iām a little annoyed with myself for not thinking of this solution sooner, and, I donāt mind admitting, a little embarrassed too!
When Iām developing a new feature for my blog or writing a new post I donāt need to see all of the blog posts, generally a handful of the latest posts will be enough.
So the above could now look like this š
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown-pages`,
path: process.env.NODE_ENV === `development` ? `${__dirname}/src/content/2021` : `${__dirname}/src/content`,
},
},
`gatsby-transformer-remark`,
],
};
Using a ternary operator and testing if process.env.NODE_ENV
equals development
I can either source a smaller
amount: src/content/2021
or all of the content: src/content
Such a simple trick and I canāt believe I hadnāt thought of it before. You live an learn ay! š¤¦
Anyway, give it a go, Iām pretty sure with this little trick youāll get those all important speedy local build times back.
See you around the internet šŗ